Problems › TypeScript › validation
Score a password
The sign-up form shows a strength meter with five segments, one for each rule the password satisfies.
- One point each for: being at least 8 characters, containing a lowercase letter, containing an uppercase letter, containing a digit, and containing anything else.
- The score is therefore between 0 and 5.
passwordScore(password: string) → int
Where you start
function passwordScore(password: string): number {
}
Worked examples
| Call | Result |
|---|---|
passwordScore("abc") | 1 |
passwordScore("abcdefgh") | 2 |
passwordScore("Abcdefg1") | 4 |
passwordScore("Abcdefg1!") | 5 |
Hint
Five independent booleans, added up. No early returns.
Reference solution in TypeScript
function passwordScore(password: string): number {
let lower = false;
let upper = false;
let digit = false;
let other = false;
for (const c of password) {
if (c >= 'a' && c <= 'z') lower = true;
else if (c >= 'A' && c <= 'Z') upper = true;
else if (c >= '0' && c <= '9') digit = true;
else other = true;
}
return (password.length >= 8 ? 1 : 0) + (lower ? 1 : 0) + (upper ? 1 : 0) + (digit ? 1 : 0) + (other ? 1 : 0);
}