From 7cbb6b9c74f958b1a8a6831d09cdd7b047eaf095 Mon Sep 17 00:00:00 2001 From: Stavan Somaiya Date: Mon, 23 Nov 2026 10:14:52 +0530 Subject: [PATCH] refactor(CountLetters): lower-case the input once before tallying (R50-T006) Fixes: #6 --- String/CountLetters.js | 7 +- String/test/CountLetters.test.js | 39 ++++ work/R50-T006/CountLetters.before.js | 33 ++++ work/R50-T006/README.md | 101 ++++++++++ work/R50-T006/after-tests.txt | 2 + work/R50-T006/baseline.txt | 9 + work/R50-T006/before-tests.txt | 2 + work/R50-T006/check.py | 267 +++++++++++++++++++++++++++ work/R50-T006/commands.log | 16 ++ work/R50-T006/evidence.mjs | 96 ++++++++++ work/R50-T006/results.json | 150 +++++++++++++++ work/R50-T006/task.json | 14 ++ work/R50-T006/versions.txt | 5 + work/R50-T006/vitest-focused.json | 52 ++++++ 14 files changed, 791 insertions(+), 2 deletions(-) create mode 100644 work/R50-T006/CountLetters.before.js create mode 100644 work/R50-T006/README.md create mode 100644 work/R50-T006/after-tests.txt create mode 100644 work/R50-T006/baseline.txt create mode 100644 work/R50-T006/before-tests.txt create mode 100644 work/R50-T006/check.py create mode 100644 work/R50-T006/commands.log create mode 100644 work/R50-T006/evidence.mjs create mode 100644 work/R50-T006/results.json create mode 100644 work/R50-T006/task.json create mode 100644 work/R50-T006/versions.txt create mode 100644 work/R50-T006/vitest-focused.json diff --git a/String/CountLetters.js b/String/CountLetters.js index 6b64001505..1b8cc042ff 100644 --- a/String/CountLetters.js +++ b/String/CountLetters.js @@ -21,9 +21,12 @@ const countLetters = (str) => { throw new TypeError('Input must not contain numbers') } + // Counting is case-insensitive: lower-case the input once, then tally it. + // The guards above only admit ASCII word characters, so `for...of` visits + // exactly the characters the previous index/charAt loop visited. + const lowerCaseStr = str.toLowerCase() const obj = {} - for (let i = 0; i < str.toLowerCase().length; i++) { - const char = str.toLowerCase().charAt(i) + for (const char of lowerCaseStr) { obj[char] = (obj[char] || 0) + 1 } diff --git a/String/test/CountLetters.test.js b/String/test/CountLetters.test.js index 424dcfa31d..6e58814913 100644 --- a/String/test/CountLetters.test.js +++ b/String/test/CountLetters.test.js @@ -31,3 +31,42 @@ describe('CountLetters', () => { expect(count).toEqual({ h: 1, e: 1, l: 2, o: 1 }) }) }) + +// Regression tests written before refactoring countLetters +// (CountLetters.js line 9). Expected objects were counted by hand. +describe('countLetters contract (locked before refactor)', () => { + // Preconditions: input is a string (line 12), has no \W characters + // (line 16) and no digits (line 20). '' passes all three. + it('smallest valid input: empty string gives an empty object', () => { + expect(countLetters('')).toEqual({}) + }) + + it('ordinary input: counts are case-insensitive, keys in first-seen order', () => { + const count = countLetters('Mississippi') + expect(count).toEqual({ m: 1, i: 4, s: 4, p: 2 }) + expect(Object.keys(count)).toEqual(['m', 'i', 's', 'p']) + }) + + it('underscore is a word character, so it is counted', () => { + expect(countLetters('a_b')).toEqual({ a: 1, _: 1, b: 1 }) + }) + + it('throws the documented TypeError messages', () => { + expect(() => countLetters(0)).toThrow( + new TypeError('Input should be a string') + ) + expect(() => countLetters('two words')).toThrow( + new TypeError('Input must not contain special characters') + ) + expect(() => countLetters('h3llo')).toThrow( + new TypeError('Input must not contain numbers') + ) + }) + + it('returns a new object on each call', () => { + const first = countLetters('ab') + const second = countLetters('ab') + expect(first).toEqual({ a: 1, b: 1 }) + expect(second).not.toBe(first) + }) +}) diff --git a/work/R50-T006/CountLetters.before.js b/work/R50-T006/CountLetters.before.js new file mode 100644 index 0000000000..6b64001505 --- /dev/null +++ b/work/R50-T006/CountLetters.before.js @@ -0,0 +1,33 @@ +/** + * @function countLetters + * @description Given a string, count the number of each letter. + * @param {String} str - The input string + * @return {Object} - Object with letters and number of times + * @example countLetters("hello") => {h: 1, e: 1, l: 2, o: 1} + */ + +const countLetters = (str) => { + const specialChars = /\W/g + + if (typeof str !== 'string') { + throw new TypeError('Input should be a string') + } + + if (specialChars.test(str)) { + throw new TypeError('Input must not contain special characters') + } + + if (/\d/.test(str)) { + throw new TypeError('Input must not contain numbers') + } + + const obj = {} + for (let i = 0; i < str.toLowerCase().length; i++) { + const char = str.toLowerCase().charAt(i) + obj[char] = (obj[char] || 0) + 1 + } + + return obj +} + +export { countLetters } diff --git a/work/R50-T006/README.md b/work/R50-T006/README.md new file mode 100644 index 0000000000..4806992fac --- /dev/null +++ b/work/R50-T006/README.md @@ -0,0 +1,101 @@ +# R50-T006 — Simplify one responsibility in `countLetters` + +Source: `String/CountLetters.js`, `countLetters` (line 9, unchanged position). + +## Recorded contract (before any change) + +| Aspect | Observation | +| --------------------- | --------------------------------------------------------------------------------------------------- | +| Input | `str` — must be a string (line 12), without `\W` characters (line 16) and without digits (line 20). | +| Result | a new object mapping each lower-cased character to its count, keys in first-seen order. | +| Errors | `TypeError` with the three messages at lines 13, 17, 21. | +| Mutation | none (strings are immutable; a new object is returned). | +| External dependencies | none. | +| Quirk kept as-is | `_` is a word character, so `countLetters('a_b')` is `{ a: 1, _: 1, b: 1 }`. | + +## Fixture (expected values counted by hand before running) + +| Input | Expected | +| --------------- | ------------------------------------------------------ | +| `''` (smallest) | `{}` | +| `'Mississippi'` | `{ m: 1, i: 4, s: 4, p: 2 }`, keys `m, i, s, p` | +| `'HelLo'` | `{ h: 1, e: 1, l: 2, o: 1 }` | +| `0` | `TypeError: Input should be a string` | +| `'two words'` | `TypeError: Input must not contain special characters` | +| `'h3llo'` | `TypeError: Input must not contain numbers` | + +## The refactor (one responsibility: tallying the lower-cased input) + +Before (original lines 24-30): + +```js +const obj = {} +for (let i = 0; i < str.toLowerCase().length; i++) { + const char = str.toLowerCase().charAt(i) + obj[char] = (obj[char] || 0) + 1 +} +return obj +``` + +After (lines 24-33): + +```js +// Counting is case-insensitive: lower-case the input once, then tally it. +// The guards above only admit ASCII word characters, so `for...of` visits +// exactly the characters the previous index/charAt loop visited. +const lowerCaseStr = str.toLowerCase() +const obj = {} +for (const char of lowerCaseStr) { + obj[char] = (obj[char] || 0) + 1 +} +return obj +``` + +**The one readability improvement:** the _lower-cased input_ is now a single named value, +`lowerCaseStr`, computed once. The loop walks over it directly, instead of recomputing +`str.toLowerCase()` twice on every iteration (once in the loop condition, once to read the current +character) and indexing into it. Everything else is untouched: same algorithm, return type, key +order, errors, side effects (none) and public argument. The accumulator keeps its name `obj` so the +diff contains only this one change. + +This is a readability change, not a claimed optimisation, and not a formatting pass (only this +block of `String/CountLetters.js` changes). + +## Guard check (temporary copy only) + +`check.py` removes `.toLowerCase()` from the new line in a temp copy. The named regression +`ordinary input: counts are case-insensitive, keys in first-seen order` passes on the refactored +code and fails on the copy (`'Mississippi'` would count `M` and `m` separately). So the tests lock +down exactly the responsibility that was refactored. + +## Before/after evidence + +- `before-tests.txt`: the 11 tests (6 existing + 5 new) pass on the original code. +- `after-tests.txt`: the same 11 tests pass after the refactor. +- `evidence.mjs` compares the refactored function with an unmodified copy of the original + (`CountLetters.before.js`) on the fixture plus 300 deterministic generated strings (valid and + invalid): 0 disagreements in results, key order or error messages. + +## How to run + +From the repository root: + +```sh +python3 work/R50-T006/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 String/test/CountLetters.test.js --reporter=json --outputFile=work/R50-T006/vitest-focused.raw.json` | 11/11 passed | +| Fixture evidence | `node work/R50-T006/evidence.mjs` | 7/7 rows match | +| Mutant: case folding dropped from the refactored tally | temporary copy | killed by `ordinary input: counts are case-insensitive` | +| Repository test script | `npm test -- --reporter=json --outputFile=work/R50-T006/vitest-full.raw.json` | 11975/11975 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`. diff --git a/work/R50-T006/after-tests.txt b/work/R50-T006/after-tests.txt new file mode 100644 index 0000000000..9db85bcc28 --- /dev/null +++ b/work/R50-T006/after-tests.txt @@ -0,0 +1,2 @@ + ✓ String/test/CountLetters.test.js (11 tests) 1ms + Tests 11 passed (11) diff --git a/work/R50-T006/baseline.txt b/work/R50-T006/baseline.txt new file mode 100644 index 0000000000..e48fe07949 --- /dev/null +++ b/work/R50-T006/baseline.txt @@ -0,0 +1,9 @@ +"" -> {} +"a" -> {"a":1} +"HelLo" -> {"h":1,"e":1,"l":2,"o":1} +"Mississippi" -> {"m":1,"i":4,"s":4,"p":2} +"a_b" -> {"a":1,"_":1,"b":1} +"hello!" -> TypeError: Input must not contain special characters +"h3llo" -> TypeError: Input must not contain numbers +0 -> TypeError: Input should be a string +"two words" -> TypeError: Input must not contain special characters diff --git a/work/R50-T006/before-tests.txt b/work/R50-T006/before-tests.txt new file mode 100644 index 0000000000..3695ed5da8 --- /dev/null +++ b/work/R50-T006/before-tests.txt @@ -0,0 +1,2 @@ + ✓ String/test/CountLetters.test.js (11 tests) 2ms + Tests 11 passed (11) diff --git a/work/R50-T006/check.py b/work/R50-T006/check.py new file mode 100644 index 0000000000..b8d27d9ebf --- /dev/null +++ b/work/R50-T006/check.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +"""Focused check runner for R50-T006. + +Run from the repository root: + + python3 work/R50-T006/check.py + +Steps (everything is recorded under work/R50-T006/): + 1. Record tool versions -> versions.txt + 2. Install dependencies from the lockfile -> `npm ci --ignore-scripts` + (set SKIP_INSTALL=1 to reuse an existing node_modules) + 3. Run the focused Vitest file(s) for this task; require a non-zero test + count and zero failures -> vitest-focused.json + 4. Run evidence.mjs: literal fixture inputs against the real source, with + input / expected / actual / source line -> results.json ("fixture") + 5. Run each deliberate mutant in a temporary copy (never in the real + source); require the named regression test to pass on the original and + fail on the mutant -> results.json ("mutants") + 6. Run the repository test script in non-watch mode + (`npm test` = `vitest run`); require a non-zero test count and zero + failures -> results.json ("full_suite") + +Every command actually executed is written to commands.log. The exit status +is non-zero if any step or assertion fails (or a step times out). +""" + +import json +import os +import platform +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent.parent +CONFIG = json.loads((HERE / 'task.json').read_text()) +TASK = CONFIG['task'] +VITEST = str(ROOT / 'node_modules' / '.bin' / 'vitest') +TIMEOUT_SECONDS = 600 + +failures = [] +log = [] + + +def show(text): + """Hide machine-specific absolute paths in recorded evidence.""" + text = text.replace(str(ROOT) + os.sep, '').replace(str(ROOT), '.') + return text.replace(tempfile.gettempdir(), '$TMPDIR') + + +def run(cmd, cwd=ROOT, check=False): + """Run a command, log it exactly, and never wait forever.""" + shown = show(' '.join(cmd)) + log.append('$ ' + shown) + try: + proc = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, + timeout=TIMEOUT_SECONDS) + except subprocess.TimeoutExpired: + log.append(f' -> timed out after {TIMEOUT_SECONDS}s') + failures.append(f'timed out: {shown}') + return subprocess.CompletedProcess(cmd, 124, '', 'timeout') + log.append(f' -> exit {proc.returncode}') + if check and proc.returncode != 0: + print(proc.stdout[-4000:]) + print(proc.stderr[-4000:], file=sys.stderr) + return proc + + +def version(cmd): + try: + return run(cmd).stdout.strip().splitlines()[0] + except Exception as exc: # best effort only + return f'unavailable ({exc})' + + +def test_list(report): + return [ + {'name': t.get('fullName') or t.get('title'), 'status': t.get('status')} + for suite in report.get('testResults', []) + for t in suite.get('assertionResults', []) + ] + + +def read_report(proc, out): + if not out.exists(): + print(proc.stdout[-4000:]) + print(proc.stderr[-4000:], file=sys.stderr) + return None + report = json.loads(out.read_text()) + out.unlink() + return report + + +def summary(cmd, proc, report): + return { + 'command': show(' '.join(cmd)), + 'exit': proc.returncode, + 'total': report and report['numTotalTests'], + 'passed': report and report['numPassedTests'], + 'failed': report and report['numFailedTests'] + } + + +def require_green(label, info, report): + if info['exit'] != 0 or not report or report['numTotalTests'] == 0 or \ + report['numFailedTests'] != 0: + failures.append(f'{label} failed: {info}') + if report: + failures.extend(' failed: ' + t['name'] + for t in test_list(report) + if t['status'] == 'failed') + + +def main(): + results = {'task': TASK} + + # 1. Tool versions + versions = { + 'python': platform.python_version(), + 'node': version(['node', '--version']), + 'npm': version(['npm', '--version']), + 'platform': platform.platform() + } + + # 2. Install from the lockfile + if os.environ.get('SKIP_INSTALL') == '1': + results['install'] = 'skipped (SKIP_INSTALL=1)' + else: + cmd = ['npm', 'ci', '--ignore-scripts', '--no-audit', '--no-fund'] + proc = run(cmd, check=True) + results['install'] = {'command': ' '.join(cmd), + 'exit': proc.returncode} + if proc.returncode != 0: + failures.append('npm ci failed') + return finish(results, versions) + versions['vitest'] = version([VITEST, '--version']) + + # 3. Focused tests + out = HERE / 'vitest-focused.raw.json' + cmd = [VITEST, 'run', *CONFIG['focused_tests'], '--reporter=json', + f'--outputFile={out}'] + proc = run(cmd) + focused_report = read_report(proc, out) + results['focused_tests'] = summary(cmd, proc, focused_report) + require_green('focused tests', results['focused_tests'], focused_report) + if focused_report: + (HERE / 'vitest-focused.json').write_text(json.dumps({ + 'command': results['focused_tests']['command'], + 'numTotalTests': focused_report['numTotalTests'], + 'numPassedTests': focused_report['numPassedTests'], + 'numFailedTests': focused_report['numFailedTests'], + 'tests': test_list(focused_report) + }, indent=2) + '\n') + + # 4. Fixture evidence (input / expected / actual / source line) + proc = run(['node', str(HERE / 'evidence.mjs')]) + rows = [] + if proc.returncode != 0: + failures.append('evidence.mjs crashed: ' + show(proc.stderr[-2000:])) + else: + rows = json.loads(proc.stdout) + results['fixture'] = rows + for row in rows: + print(f"[{'PASS' if row['pass'] else 'FAIL'}] {row['name']}") + print(f" input: {json.dumps(row['input'])}") + print(f" expected: {json.dumps(row['expected'])}") + print(f" actual: {json.dumps(row['actual'])}") + if row.get('precondition'): + print(f" source: {row['precondition']}") + if not row['pass']: + failures.append(f"fixture mismatch: {row['name']}") + if not rows: + failures.append('no fixture rows were produced') + + # 5. Deliberate mutants, in temporary copies only + original_tests = test_list(focused_report) if focused_report else [] + mutants = [run_mutant(m, original_tests) for m in CONFIG.get('mutants', [])] + if mutants: + results['mutants'] = mutants + + # 6. Repository test script in non-watch mode: `npm test` (vitest run) + out = HERE / 'vitest-full.raw.json' + cmd = ['npm', 'test', '--', '--reporter=json', f'--outputFile={out}'] + proc = run(cmd) + full_report = read_report(proc, out) + results['full_suite'] = summary(cmd, proc, full_report) + require_green('repository test script', results['full_suite'], full_report) + + return finish(results, versions) + + +def run_mutant(mutant, original_tests): + """Copy the source and its tests into a temp dir, apply one edit there, + and require the named test to pass on the original and fail here.""" + original = (ROOT / mutant['file']).read_text() + named = [t for t in original_tests if mutant['must_fail'] in t['name']] + entry = { + 'name': mutant['name'], + 'file': mutant['file'], + 'edit': {'from': mutant['find'], 'to': mutant['replace']}, + 'named_test': mutant['must_fail'], + 'named_test_on_original': [t['status'] for t in named], + 'killed': False + } + if len(named) != 1 or named[0]['status'] != 'passed': + failures.append(f"mutant {mutant['name']}: named test must match " + f"exactly one passing test on the original") + return entry + if original.count(mutant['find']) != 1: + failures.append(f"mutant {mutant['name']}: edit must match once") + return entry + with tempfile.TemporaryDirectory(prefix=f'{TASK}-mutant-') as tmp: + tmp = Path(tmp) + for rel in [mutant['file'], *mutant['tests']]: + dest = tmp / rel + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copy(ROOT / rel, dest) + (tmp / mutant['file']).write_text( + original.replace(mutant['find'], mutant['replace'])) + out = tmp / 'mutant-report.json' + cmd = [VITEST, 'run', *mutant['tests'], '--root', str(tmp), + '--globals', '--reporter=json', f'--outputFile={out}'] + proc = run(cmd) + report = read_report(proc, out) + failed = [t['name'] for t in test_list(report) + if t['status'] == 'failed'] if report else [] + entry['exit'] = proc.returncode + entry['failed_tests_on_mutant'] = failed + entry['killed'] = proc.returncode != 0 and any( + mutant['must_fail'] in name for name in failed) + print(f"[{'KILLED' if entry['killed'] else 'SURVIVED'}] mutant " + f"{mutant['name']}: {mutant['find']!r} -> {mutant['replace']!r}") + for name in failed: + print(f' failed: {name}') + if not entry['killed']: + failures.append(f"mutant {mutant['name']} was not detected by " + f"'{mutant['must_fail']}'") + return entry + + +def finish(results, versions): + results['ok'] = not failures + results['failures'] = failures + (HERE / 'versions.txt').write_text( + ''.join(f'{k}: {v}\n' for k, v in versions.items())) + (HERE / 'results.json').write_text(json.dumps(results, indent=2) + '\n') + (HERE / 'commands.log').write_text('\n'.join(log) + '\n') + print() + for key, label in [('focused_tests', 'focused tests'), + ('full_suite', 'npm test')]: + if key in results: + info = results[key] + print(f"{label + ':':15}{info['passed']}/{info['total']} passed" + f" ({info['command']})") + if failures: + print('\nFAILED:') + for item in failures: + print(' - ' + item) + return 1 + print(f'\n{TASK}: all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/work/R50-T006/commands.log b/work/R50-T006/commands.log new file mode 100644 index 0000000000..84745203d8 --- /dev/null +++ b/work/R50-T006/commands.log @@ -0,0 +1,16 @@ +$ node --version + -> exit 0 +$ npm --version + -> exit 0 +$ npm ci --ignore-scripts --no-audit --no-fund + -> exit 0 +$ node_modules/.bin/vitest --version + -> exit 0 +$ node_modules/.bin/vitest run String/test/CountLetters.test.js --reporter=json --outputFile=work/R50-T006/vitest-focused.raw.json + -> exit 0 +$ node work/R50-T006/evidence.mjs + -> exit 0 +$ node_modules/.bin/vitest run String/test/CountLetters.test.js --root $TMPDIR/R50-T006-mutant-0x_89v8u --globals --reporter=json --outputFile=$TMPDIR/R50-T006-mutant-0x_89v8u/mutant-report.json + -> exit 1 +$ npm test -- --reporter=json --outputFile=work/R50-T006/vitest-full.raw.json + -> exit 0 diff --git a/work/R50-T006/evidence.mjs b/work/R50-T006/evidence.mjs new file mode 100644 index 0000000000..49f513ca72 --- /dev/null +++ b/work/R50-T006/evidence.mjs @@ -0,0 +1,96 @@ +// R50-T006 evidence: the fixture against the refactored countLetters, and a +// before/after comparison against an unmodified copy of the original +// (CountLetters.before.js, copied from the pinned commit before editing). +import { countLetters } from '../../String/CountLetters.js' +import { countLetters as countLettersBefore } from './CountLetters.before.js' + +const SRC = 'CountLetters.js' +const call = (fn, x) => { + try { + const result = fn(x) + return { result, keys: Object.keys(result) } + } catch (e) { + return { error: `${e.constructor.name}: ${e.message}` } + } +} +const same = (a, b) => JSON.stringify(a) === JSON.stringify(b) + +const fixture = [ + [ + 'smallest valid input', + '', + { result: {}, keys: [] }, + `${SRC}:12,16,20 '' passes all guards` + ], + [ + 'ordinary input', + 'Mississippi', + { result: { m: 1, i: 4, s: 4, p: 2 }, keys: ['m', 'i', 's', 'p'] }, + `${SRC}:16,20 letters only` + ], + [ + 'mixed case', + 'HelLo', + { result: { h: 1, e: 1, l: 2, o: 1 }, keys: ['h', 'e', 'l', 'o'] }, + `${SRC}:27 counting is case-insensitive` + ], + [ + 'non-string', + 0, + { error: 'TypeError: Input should be a string' }, + `${SRC}:12-13` + ], + [ + 'special character', + 'two words', + { error: 'TypeError: Input must not contain special characters' }, + `${SRC}:16-17` + ], + [ + 'digit', + 'h3llo', + { error: 'TypeError: Input must not contain numbers' }, + `${SRC}:20-21` + ] +] + +const rows = fixture.map(([name, input, expected, precondition]) => { + const actual = call(countLetters, input) + return { + name, + input, + expected, + actual, + pass: same(actual, expected), + precondition + } +}) + +// Before/after agreement on the fixture plus 300 deterministic inputs. +let seed = 6 +const random = () => { + seed = (seed * 1103515245 + 12345) % 2147483648 + return seed / 2147483648 +} +const alphabet = 'abcXYZ_eE 1!' +const inputs = fixture.map((f) => f[1]) +for (let n = 0; n < 300; n++) { + let s = '' + const length = Math.floor(random() * 10) + for (let k = 0; k < length; k++) + s += alphabet[Math.floor(random() * alphabet.length)] + inputs.push(s) +} +const disagreements = inputs.filter( + (x) => !same(call(countLetters, x), call(countLettersBefore, x)) +) +rows.push({ + name: 'before/after agree (results, key order, errors)', + input: `${inputs.length} inputs (fixture + 300 generated)`, + expected: [], + actual: disagreements, + pass: disagreements.length === 0, + precondition: `${SRC}:9 public signature unchanged` +}) + +console.log(JSON.stringify(rows)) diff --git a/work/R50-T006/results.json b/work/R50-T006/results.json new file mode 100644 index 0000000000..a021c18dd6 --- /dev/null +++ b/work/R50-T006/results.json @@ -0,0 +1,150 @@ +{ + "task": "R50-T006", + "install": { + "command": "npm ci --ignore-scripts --no-audit --no-fund", + "exit": 0 + }, + "focused_tests": { + "command": "node_modules/.bin/vitest run String/test/CountLetters.test.js --reporter=json --outputFile=work/R50-T006/vitest-focused.raw.json", + "exit": 0, + "total": 11, + "passed": 11, + "failed": 0 + }, + "fixture": [ + { + "name": "smallest valid input", + "input": "", + "expected": { + "result": {}, + "keys": [] + }, + "actual": { + "result": {}, + "keys": [] + }, + "pass": true, + "precondition": "CountLetters.js:12,16,20 '' passes all guards" + }, + { + "name": "ordinary input", + "input": "Mississippi", + "expected": { + "result": { + "m": 1, + "i": 4, + "s": 4, + "p": 2 + }, + "keys": ["m", "i", "s", "p"] + }, + "actual": { + "result": { + "m": 1, + "i": 4, + "s": 4, + "p": 2 + }, + "keys": ["m", "i", "s", "p"] + }, + "pass": true, + "precondition": "CountLetters.js:16,20 letters only" + }, + { + "name": "mixed case", + "input": "HelLo", + "expected": { + "result": { + "h": 1, + "e": 1, + "l": 2, + "o": 1 + }, + "keys": ["h", "e", "l", "o"] + }, + "actual": { + "result": { + "h": 1, + "e": 1, + "l": 2, + "o": 1 + }, + "keys": ["h", "e", "l", "o"] + }, + "pass": true, + "precondition": "CountLetters.js:27 counting is case-insensitive" + }, + { + "name": "non-string", + "input": 0, + "expected": { + "error": "TypeError: Input should be a string" + }, + "actual": { + "error": "TypeError: Input should be a string" + }, + "pass": true, + "precondition": "CountLetters.js:12-13" + }, + { + "name": "special character", + "input": "two words", + "expected": { + "error": "TypeError: Input must not contain special characters" + }, + "actual": { + "error": "TypeError: Input must not contain special characters" + }, + "pass": true, + "precondition": "CountLetters.js:16-17" + }, + { + "name": "digit", + "input": "h3llo", + "expected": { + "error": "TypeError: Input must not contain numbers" + }, + "actual": { + "error": "TypeError: Input must not contain numbers" + }, + "pass": true, + "precondition": "CountLetters.js:20-21" + }, + { + "name": "before/after agree (results, key order, errors)", + "input": "306 inputs (fixture + 300 generated)", + "expected": [], + "actual": [], + "pass": true, + "precondition": "CountLetters.js:9 public signature unchanged" + } + ], + "mutants": [ + { + "name": "case folding dropped from the refactored tally", + "file": "String/CountLetters.js", + "edit": { + "from": " const lowerCaseStr = str.toLowerCase()\n", + "to": " const lowerCaseStr = str\n" + }, + "named_test": "ordinary input: counts are case-insensitive", + "named_test_on_original": ["passed"], + "killed": true, + "exit": 1, + "failed_tests_on_mutant": [ + " CountLetters count the letters in a string. Allows upper case", + " CountLetters count the letters in a string. Allows upper and lower case", + " countLetters contract (locked before refactor) ordinary input: counts are case-insensitive, keys in first-seen order" + ] + } + ], + "full_suite": { + "command": "npm test -- --reporter=json --outputFile=work/R50-T006/vitest-full.raw.json", + "exit": 0, + "total": 11975, + "passed": 11975, + "failed": 0 + }, + "ok": true, + "failures": [] +} diff --git a/work/R50-T006/task.json b/work/R50-T006/task.json new file mode 100644 index 0000000000..0d65c08336 --- /dev/null +++ b/work/R50-T006/task.json @@ -0,0 +1,14 @@ +{ + "task": "R50-T006", + "focused_tests": ["String/test/CountLetters.test.js"], + "mutants": [ + { + "name": "case folding dropped from the refactored tally", + "file": "String/CountLetters.js", + "find": " const lowerCaseStr = str.toLowerCase()\n", + "replace": " const lowerCaseStr = str\n", + "tests": ["String/test/CountLetters.test.js"], + "must_fail": "ordinary input: counts are case-insensitive" + } + ] +} diff --git a/work/R50-T006/versions.txt b/work/R50-T006/versions.txt new file mode 100644 index 0000000000..b405ff9cb4 --- /dev/null +++ b/work/R50-T006/versions.txt @@ -0,0 +1,5 @@ +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 diff --git a/work/R50-T006/vitest-focused.json b/work/R50-T006/vitest-focused.json new file mode 100644 index 0000000000..87f5911375 --- /dev/null +++ b/work/R50-T006/vitest-focused.json @@ -0,0 +1,52 @@ +{ + "command": "node_modules/.bin/vitest run String/test/CountLetters.test.js --reporter=json --outputFile=work/R50-T006/vitest-focused.raw.json", + "numTotalTests": 11, + "numPassedTests": 11, + "numFailedTests": 0, + "tests": [ + { + "name": " CountLetters expect throws on use wrong param", + "status": "passed" + }, + { + "name": " CountLetters expect throws when using a number in the string", + "status": "passed" + }, + { + "name": " CountLetters expect throws when using a special characters in the string", + "status": "passed" + }, + { + "name": " CountLetters count the letters in a string. Allows lower case", + "status": "passed" + }, + { + "name": " CountLetters count the letters in a string. Allows upper case", + "status": "passed" + }, + { + "name": " CountLetters count the letters in a string. Allows upper and lower case", + "status": "passed" + }, + { + "name": " countLetters contract (locked before refactor) smallest valid input: empty string gives an empty object", + "status": "passed" + }, + { + "name": " countLetters contract (locked before refactor) ordinary input: counts are case-insensitive, keys in first-seen order", + "status": "passed" + }, + { + "name": " countLetters contract (locked before refactor) underscore is a word character, so it is counted", + "status": "passed" + }, + { + "name": " countLetters contract (locked before refactor) throws the documented TypeError messages", + "status": "passed" + }, + { + "name": " countLetters contract (locked before refactor) returns a new object on each call", + "status": "passed" + } + ] +}