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
33 changes: 25 additions & 8 deletions Ciphers/KeywordShiftedAlphabet.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
* Second row start with the keyword, then we continue with the rest of the characters that are missing in alphabetical order.
*
* |A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|
* |K|E|Y|W|O|R|D|A|B|C|F|G|H|I|J|L|M|N|P|Q|S|T|U|V|W|Z|
* |K|E|Y|W|O|R|D|A|B|C|F|G|H|I|J|L|M|N|P|Q|S|T|U|V|X|Z|
*
* Encryption is then just a matter of writing the matching (same index) letter from the second row instead of the first row:
* 'Hello world' -> 'Aoggj ujngw'
*
* Decryption is then just the reverse process of writing the matching (same index) letter from the first row instead of the second row
* 'Aogg ujngw' -> 'Hello world'
* 'Aoggj ujngw' -> 'Hello world'
*
* Non alphabetical characters (space, exclamation mark, ...) are kept as they are
*/
Expand Down Expand Up @@ -45,14 +45,31 @@ const alphabet = [
'z'
]

/**
* Checks the keyword rule stated at the top of this file:
* "Keyword must be a word where each character can occur only once."
*
* Supported boundaries:
* - 'a' (one character) is the smallest valid keyword -> true
* - a keyword using all 26 letters once is the largest valid keyword -> true
* - any repeated character, e.g. 'aa' or 'hello', is invalid -> false
* - '' is never reached through encrypt/decrypt: checkInputs rejects it first
* with 'Both keyword and message must be specified'.
* Characters are compared exactly as given (no case folding).
*
* @param {string} keyword
* @returns {boolean} true when no character occurs more than once
* @example checkKeywordValidity('keyword') // true
* @example checkKeywordValidity('hello') // false ('l' repeats)
*/
function checkKeywordValidity(keyword) {
keyword.split('').forEach((char, index) => {
// `every` stops and returns false on the first repeated character.
// (A `return false` inside `forEach` only left the callback, so repeated
// characters were previously accepted.)
return keyword.split('').every((char, index) => {
const rest = keyword.slice(0, index) + keyword.slice(index + 1)
if (rest.indexOf(char) !== -1) {
return false
}
return rest.indexOf(char) === -1
})
return true
}

function getEncryptedAlphabet(keyword) {
Expand Down Expand Up @@ -106,7 +123,7 @@ function decrypt(keyword, message) {
)
}

export { encrypt, decrypt }
export { encrypt, decrypt, checkKeywordValidity }

// encrypt('keyword', 'Hello world!') // Prints 'Aoggj ujngw!'
// decrypt('keyword', 'Aoggj ujngw!') // Prints 'Hello world!
54 changes: 53 additions & 1 deletion Ciphers/test/KeywordShiftedAlphabet.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { encrypt, decrypt } from '../KeywordShiftedAlphabet'
import {
encrypt,
decrypt,
checkKeywordValidity
} from '../KeywordShiftedAlphabet'

test('Hello world! === decrypt(encrypt(Hello world!))', () => {
const word = 'Hello world!'
Expand All @@ -11,3 +15,51 @@ test('The Algorithms === decrypt(encrypt(The Algorithms))', () => {
const result = decrypt('keyword', encrypt('keyword', word))
expect(result).toMatch(word)
})

// Boundary tests for checkKeywordValidity (KeywordShiftedAlphabet.js line 65).
// Contract (line 3): "Keyword must be a word where each character can occur
// only once." Empty input is rejected earlier by checkInputs (line 99).
describe('checkKeywordValidity boundaries', () => {
describe('valid side', () => {
test("smallest valid keyword 'a' is accepted", () => {
expect(checkKeywordValidity('a')).toBe(true)
// 'a' leaves the alphabet unchanged, so encryption is the identity.
expect(encrypt('a', 'abc')).toBe('abc')
})

test("ordinary keyword 'keyword' is accepted", () => {
expect(checkKeywordValidity('keyword')).toBe(true)
// Table at line 8: H->A, E->O, L->G, O->J, W->U, R->N, D->W
expect(encrypt('keyword', 'Hello world!')).toBe('Aoggj ujngw!')
})

test('largest valid keyword uses all 26 letters exactly once', () => {
const reversed = 'zyxwvutsrqponmlkjihgfedcba'
expect(checkKeywordValidity(reversed)).toBe(true)
expect(encrypt(reversed, 'abc')).toBe('zyx')
})
})

describe('invalid side', () => {
test("smallest repeated keyword 'aa' is rejected", () => {
expect(checkKeywordValidity('aa')).toBe(false)
expect(() => encrypt('aa', 'abc')).toThrow('Invalid keyword!')
expect(() => decrypt('aa', 'abc')).toThrow('Invalid keyword!')
})

test("ordinary repeated keyword 'hello' is rejected", () => {
expect(checkKeywordValidity('hello')).toBe(false)
expect(() => encrypt('hello', 'd')).toThrow('Invalid keyword!')
})

test('a 27th letter must repeat one of the 26 and is rejected', () => {
expect(checkKeywordValidity('zyxwvutsrqponmlkjihgfedcbaa')).toBe(false)
})

test('empty keyword is rejected by checkInputs before validity', () => {
expect(() => encrypt('', 'abc')).toThrow(
'Both keyword and message must be specified'
)
})
})
})
84 changes: 84 additions & 0 deletions work/R50-T002/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# R50-T002 — Supported boundaries of `checkKeywordValidity`

Source: `Ciphers/KeywordShiftedAlphabet.js`, `checkKeywordValidity` (line 65 after this change; line 48 at pinned commit `5c39e87`).

## Recorded contract (before any change)

| Aspect | Observation |
| --------------------- | -------------------------------------------------------------------------------------------------- |
| Input | `keyword` (string). Only called from `checkInputs`, after the empty-input guard (line 99). |
| Result | boolean — "Keyword must be a word where each character can occur only once" (line 3). |
| Mutation | None (strings are immutable). |
| External dependencies | None. |
| Public interface | `encrypt`, `decrypt` (unchanged). `checkKeywordValidity` is now also exported so it can be tested. |

## Boundary table (expected values written before running the source)

| Partition | Input | Expected | Source contract |
| ------------------------- | ------------------------------ | -------------------------------------------------------------- | --------------- |
| valid boundary (smallest) | `'a'` | `true`; `encrypt('a','abc') === 'abc'` | line 3 |
| valid interior | `'keyword'` | `true`; `encrypt('keyword','Hello world!') === 'Aoggj ujngw!'` | lines 3, 8 |
| valid boundary (largest) | `'zyxwvutsrqponmlkjihgfedcba'` | `true`; `encrypt(…,'abc') === 'zyx'` | line 3 |
| invalid boundary | `'aa'` | `false`; `encrypt` throws `Invalid keyword!` | lines 3, 104 |
| invalid interior | `'hello'` | `false`; `encrypt` throws `Invalid keyword!` | lines 3, 104 |
| invalid (27 letters) | 26 letters + `'a'` | `false` | line 3 |
| unsupported (empty) | `''` | `encrypt` throws `Both keyword and message must be specified` | line 99-100 |

Not covered on purpose: mixed-case repeats such as `'Aa'` and non-letter keywords. The source does
not define them, so no new rule was added for them.

## Baseline — defect found

Running the fixture against the original source (`baseline.txt`):

- `encrypt('aa', 'abc')` returned `"aab"` instead of throwing `Invalid keyword!`.
- `encrypt('hello', 'd')` returned `"l"` instead of throwing.
- Round trip broke: `decrypt('hello', encrypt('hello', 'd'))` returned `"c"`, not `"d"`.

Cause: `return false` inside `keyword.split('').forEach(...)` only returns from the callback, so the
function always reached `return true`.

Order of work and evidence: the baseline above was recorded on the original, unedited source.
The expected values in the boundary tests come from the documented contract (line 3), not from
running the fixed code. `negative-control.txt` shows `check.py` run with the original
always-`true` behaviour put back temporarily: it exits **1** and names the 3 failing
repeated-keyword tests, while the other 6 tests pass. With the fix, all pass.

The fix replaces `forEach` with `every`, which stops and returns `false` on the first repeated
character. It uses the same algorithm and the same case-sensitive comparison. No guard was added
elsewhere.

Documentation corrections in the same header (both confirmed by running the code):

- line 8: the translation-table row listed `W` twice and omitted `X` (`…U|V|W|Z|` → `…U|V|X|Z|`);
- line 14: the decryption example was missing a letter (`'Aogg ujngw'` → `'Aoggj ujngw'`).

## Sensitivity check (temporary copy only)

On every run, `check.py` also applies the original defect (`return true` for every character) to a
temp copy of the source. The named test `smallest repeated keyword 'aa' is rejected` passes on the
fixed code and fails on that copy.

## How to run

From the repository root:

```sh
python3 work/R50-T002/check.py
```

`check.py` installs dependencies from `package-lock.json`, runs the focused test file, evaluates the fixture with `evidence.mjs` (input, expected, actual and source line for every case), runs each deliberate mutant in a temporary copy, and finally runs the repository test script in non-watch mode (`npm test`, which is `vitest run`). It exits non-zero if any assertion or step fails, and records every command it ran in `commands.log`.

### Recorded run (files in this folder)

| Step | Command | Result |
| ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ |
| Install from lockfile | `npm ci --ignore-scripts --no-audit --no-fund` (exit 0) | ok |
| Focused tests | `node_modules/.bin/vitest run Ciphers/test/KeywordShiftedAlphabet.test.js --reporter=json --outputFile=work/R50-T002/vitest-focused.raw.json` | 9/9 passed |
| Fixture evidence | `node work/R50-T002/evidence.mjs` | 10/10 rows match |
| Mutant: original defect restored (every character accepted) | temporary copy | killed by `smallest repeated keyword 'aa' is rejected` |
| Repository test script | `npm test -- --reporter=json --outputFile=work/R50-T002/vitest-full.raw.json` | 11977/11977 passed |

Tool versions (`versions.txt`): python 3.12.10; node v26.13.1; npm 11.20.0; platform macOS-27.2.1-arm64-arm-64bit; vitest vitest/1.2.1 darwin-arm64 node-v26.13.1.

Files: `results.json` (all of the above, machine-readable), `vitest-focused.json` (each focused test and its status), `commands.log`, `versions.txt`.
8 changes: 8 additions & 0 deletions work/R50-T002/baseline.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Baseline: ORIGINAL Ciphers/KeywordShiftedAlphabet.js (pinned commit 5c39e87), via encrypt()
encrypt("a", "abc") -> "abc"
encrypt("keyword", "Hello world!") -> "Aoggj ujngw!"
encrypt("zyxwvutsrqponmlkjihgfedcba", "abc") -> "zyx"
encrypt("", "abc") -> throws: Both keyword and message must be specified
encrypt("aa", "abc") -> "aab"
encrypt("hello", "d") -> "l"
round trip with repeated keyword: decrypt("hello", encrypt("hello", "d")) -> "c" (expected "d")
Loading