Skip to content

Commit 6507502

Browse files
authored
fix: actually reject KeywordShiftedAlphabet keywords with repeated characters
checkKeywordValidity returned false inside a forEach callback, which only exits the callback, so it always returned true and repeated-character keywords were accepted. With such a keyword the translation table is not a bijection and encryption loses information: encrypt('HELLO', 'ATTACK AT DAWN') gave 'HSSHLG HS LHVK', which decrypted to 'ATTACK AT CAWN'. Validate the lowercased keyword with every() so each character must be the first occurrence of itself; this also closes the 'Kk' case hole.
1 parent 5c39e87 commit 6507502

1 file changed

Lines changed: 6 additions & 7 deletions

File tree

‎Ciphers/KeywordShiftedAlphabet.js‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,12 @@ const alphabet = [
4646
]
4747

4848
function checkKeywordValidity(keyword) {
49-
keyword.split('').forEach((char, index) => {
50-
const rest = keyword.slice(0, index) + keyword.slice(index + 1)
51-
if (rest.indexOf(char) !== -1) {
52-
return false
53-
}
54-
})
55-
return true
49+
// Compare case-insensitively: the translation table is built from the
50+
// lowercased keyword, so 'Kk' would collapse to a duplicate there.
51+
const chars = keyword.toLowerCase().split('')
52+
// forEach cannot return early, so use every: each character must be the
53+
// first occurrence of itself.
54+
return chars.every((char, index) => chars.indexOf(char) === index)
5655
}
5756

5857
function getEncryptedAlphabet(keyword) {

0 commit comments

Comments
 (0)