Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions Ciphers/KeywordShiftedAlphabet.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,12 @@ const alphabet = [
]

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

function getEncryptedAlphabet(keyword) {
Expand Down
12 changes: 12 additions & 0 deletions Ciphers/test/KeywordShiftedAlphabet.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,15 @@ test('The Algorithms === decrypt(encrypt(The Algorithms))', () => {
const result = decrypt('keyword', encrypt('keyword', word))
expect(result).toMatch(word)
})

test('rejects keywords with repeated characters', () => {
// 'HELLO' repeats L; encrypt must throw instead of producing
// ciphertext that cannot be decrypted back
expect(() => encrypt('HELLO', 'ATTACK AT DAWN')).toThrow('Invalid keyword!')
expect(() => decrypt('HELLO', 'HSSHLG HS LHVK')).toThrow('Invalid keyword!')
})

test('rejects keywords that repeat a character in another case', () => {
// the table is built from the lowercased keyword, so 'Kk' is a duplicate
expect(() => encrypt('Kk', 'ATTACK')).toThrow('Invalid keyword!')
})
Loading