Skip to content

Commit 39e4f1b

Browse files
committed
[LES-16.6/st-compl] principle-of-closure
Practice/understanding "closure". Returning obj, func. Worth noting: - order of "if/else" blocks. FS-dev: B-3 / JS basic
1 parent 9a8f185 commit 39e4f1b

File tree

1 file changed

+72
-0
lines changed
  • full-stack-dev/3-js-basic/16-managing-this/16-6-principle-of-closure

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
'use strict';
2+
3+
// Задание 1:
4+
// Напиши функцию createLogger(prefix).
5+
// 1. Эта функция должна принимать один аргумент — строку prefix.
6+
// 2. Она должна возвращать объект с двумя методами: log(message) и warn(message).
7+
// 3. При вызове logger.log("some text") в консоль должно выводиться: [<prefix>] some text.
8+
// 4. При вызове logger.warn("some warning") в консоль должно выводиться: [<prefix>] WARNING: some warning.
9+
10+
function createLogger(prefix) {
11+
return {
12+
log(message) {
13+
return `[${prefix}] ${message}`;
14+
},
15+
warn(message) {
16+
return `[${prefix}] WARNING: ${message}`;
17+
},
18+
};
19+
}
20+
21+
const appLogger = createLogger('MyApp');
22+
console.log(appLogger.log('User logged in')); // [MyApp] User logged in
23+
console.log(appLogger.warn('Disk space low')); // [MyApp] WARNING: Disk space low
24+
25+
const dbLogger = createLogger('Database');
26+
console.log(dbLogger.log('Query successful')); // [Database] Query successful
27+
28+
// Задание 2:
29+
// Напиши функцию createPasswordChecker(validPassword).
30+
// 1. Она принимает один аргумент — правильный пароль (строку).
31+
// 2 .Она должна возвращать другую функцию, которая будет принимать пароль для проверки.
32+
// 3. Эта внутренняя функция должна вести себя так:
33+
// - При первом вызове с неверным паролем она должна возвращать строку: "Wrong password. You have 2 attempts left."
34+
// - При втором вызове с неверным паролем: "Wrong password. You have 1 attempt left."
35+
// - При третьем вызове с неверным паролем: "Access denied." Все последующие вызовы (четвертый, пятый...) также должны возвращать "Access denied."
36+
// - Если в любой момент вводится верный пароль, она должна вернуть "Access granted." и "сбросить" счетчик попыток на будущее (хотя это уже не так важно, главное — предоставить доступ).
37+
// Намёк: Тебе понадобится переменная-счетчик внутри замыкания, чтобы отслеживать количество оставшихся попыток.
38+
39+
function createPasswordChecker(validPassword) {
40+
let attemptsLeft = 3;
41+
42+
return function (password) {
43+
if (attemptsLeft === 0) {
44+
return 'Access denied.';
45+
}
46+
47+
if (password === validPassword) {
48+
attemptsLeft = 3;
49+
return 'Access granted.';
50+
}
51+
52+
attemptsLeft--;
53+
54+
if (attemptsLeft > 0) {
55+
return `Wrong password. You have ${attemptsLeft} attempt(s) left.`;
56+
} else {
57+
return 'Access denied.';
58+
}
59+
};
60+
}
61+
62+
const checkPassword = createPasswordChecker('12345');
63+
64+
console.log(checkPassword('wrong')); // "Wrong password. You have 2 attempts left."
65+
console.log(checkPassword('still-wrong')); // "Wrong password. You have 1 attempt left."
66+
console.log(checkPassword('12345')); // "Access granted."
67+
68+
const checkAnotherPassword = createPasswordChecker('qwerty');
69+
console.log(checkAnotherPassword('wrong')); // "Wrong password. You have 2 attempts left."
70+
console.log(checkAnotherPassword('still-wrong')); // "Wrong password. You have 1 attempt left."
71+
console.log(checkAnotherPassword('final-wrong')); // "Access denied."
72+
console.log(checkAnotherPassword('qwerty')); // "Access denied." (Доступ уже заблокирован)

0 commit comments

Comments
 (0)