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
17 changes: 16 additions & 1 deletion Data-Structures/Tree/Trie.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,18 @@
/**
* One node of the Trie: a single character (`key`), how many inserted words
* end exactly here (`count`), its `children` keyed by character and its
* `parent` (`null` for the root or when no parent is given).
*
* Absent results: the Trie never throws for a missing word. Instead,
* - `findPrefix` returns `null` when some character of the prefix has no
* child node, e.g. 'cab' after inserting 'car' and 'cat';
* - a node that exists only as a prefix (e.g. 'ca') has `count === 0`, so
* `contains('ca')` is `false` and `findOccurrences('ca')` is `0`.
* Lookups never create nodes, so a failed lookup leaves the Trie unchanged.
*
* @param {string|null} key character stored in this node (`null` for root)
* @param {TrieNode|null} [parent] parent node; omitted means `null`
*/
class TrieNode {
constructor(key, parent) {
this.key = key
Expand Down Expand Up @@ -129,4 +144,4 @@ class Trie {
}
}

export { Trie }
export { Trie, TrieNode }
94 changes: 94 additions & 0 deletions Data-Structures/Tree/test/Trie.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { Trie, TrieNode } from '../Trie'

// Fixture: insert "car", "cat" and "dog".
const buildTrie = () => {
const trie = new Trie()
trie.insert('car')
trie.insert('cat')
trie.insert('dog')
return trie
}

describe('TrieNode', () => {
// Trie.js lines 21-22: an omitted parent becomes null.
it('a node created without a parent has parent null and count 0', () => {
const node = new TrieNode('c')
expect(node.key).toBe('c')
expect(node.parent).toBeNull()
expect(node.count).toBe(0)
expect(Object.keys(node.children)).toEqual([])
})

it('a child node keeps a reference to its parent', () => {
const root = new TrieNode(null, null)
const child = new TrieNode('c', root)
expect(child.parent).toBe(root)
})
})

describe('Trie absent-result paths (no exceptions are thrown)', () => {
// Branch under test: findPrefix returns null at Trie.js line 76
// ("No such prefix exists") when a character has no child node.
it("missing word 'cab' reaches the null branch of findPrefix", () => {
const trie = buildTrie()
// 'c' and 'a' exist, 'b' does not: the loop stops at i = 2.
expect(trie.findPrefix('ca')).toBeInstanceOf(TrieNode)
expect(trie.findPrefix('cab')).toBeNull()
expect(trie.contains('cab')).toBe(false) // line 135
expect(trie.findOccurrences('cab')).toBe(0) // line 142
expect(trie.findAllWords('cab')).toEqual([]) // line 126
})

// Branch under test: node exists but count is 0 (Trie.js line 135).
it("prefix 'ca' is not a complete word, but 'car' is", () => {
const trie = buildTrie()
const prefixNode = trie.findPrefix('ca')
expect(prefixNode.count).toBe(0)
expect(trie.contains('ca')).toBe(false)
expect(trie.findOccurrences('ca')).toBe(0)
expect(trie.contains('car')).toBe(true)
expect(trie.findOccurrences('car')).toBe(1)
})

it('non-string input is ignored, not thrown (lines 52 and 70)', () => {
const trie = buildTrie()
expect(trie.insert(5)).toBeUndefined()
expect(trie.findPrefix(5)).toBeNull()
expect(trie.findAllWords('')).toEqual([
{ word: 'car', count: 1 },
{ word: 'cat', count: 1 },
{ word: 'dog', count: 1 }
])
})

it('failed lookups leave the trie unchanged and later calls succeed', () => {
const trie = buildTrie()

expect(trie.contains('cab')).toBe(false)
expect(trie.findPrefix('zebra')).toBeNull()
expect(trie.findAllWords('')).toEqual([
{ word: 'car', count: 1 },
{ word: 'cat', count: 1 },
{ word: 'dog', count: 1 }
])
expect(trie.findPrefix('cab')).toBeNull() // no node was created

// An ordinary valid call after the failure.
trie.insert('cab')
expect(trie.contains('cab')).toBe(true)
expect(trie.findOccurrences('cab')).toBe(1)
expect(trie.contains('car')).toBe(true)
})

it('repeated insertion increments the count of the same node', () => {
const trie = buildTrie()
const node = trie.findPrefix('car')
trie.insert('car')
expect(trie.findPrefix('car')).toBe(node)
expect(trie.findOccurrences('car')).toBe(2)
expect(trie.findAllWords('ca')).toEqual([
{ word: 'car', count: 2 },
{ word: 'cat', count: 1 }
])
})
})
91 changes: 91 additions & 0 deletions work/R50-T008/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# R50-T008 — Failure / absent-result behaviour of `TrieNode`

Source: `Data-Structures/Tree/Trie.js`, `TrieNode` (line 16 after this change; line 1 at pinned commit `5c39e87`).

## Recorded contract (before any change)

| Aspect | Observation |
| ----------------------- | ----------------------------------------------------------------------------------------------------- |
| `TrieNode(key, parent)` | stores `key`, `count = 0`, prototype-less `children`; an omitted parent becomes `null` (lines 21-22). |
| Trie API | `insert`, `findPrefix`, `contains`, `findOccurrences`, `findAllWords`, `remove`. |
| Failure policy | **total**: nothing throws for a missing word. Missing results are `null`, `false`, `0` or `[]`. |
| Mutation | only `insert`/`remove` change nodes; lookups only read. |
| External dependencies | none. |
| Public interface | `Trie` unchanged; `TrieNode` is now also exported so tests can check node identity and shape. |

Because the contract is total, the tests use the documented empty / missing results rather than
inventing an exception.

## Branches exercised (source lines in the final file)

| Branch | Line | Smallest input that reaches it | Result |
| ---------------------------------------------------- | ------ | ---------------------------------------- | ------------------------------- |
| `findPrefix`: `return null // No such prefix exists` | 76 | `'cab'` after car/cat/dog (stops at `b`) | `null` |
| `contains`: `node !== null && node.count !== 0` | 135 | `'ca'` (node exists, count 0) | `false` |
| `findOccurrences`: `if (node === null) return 0` | 142 | `'cab'` | `0` |
| `findAllWords`: `if (node === null) return output` | 126 | `'cab'` | `[]` |
| non-string guard in `insert` / `findPrefix` | 52, 70 | `5` | `undefined` / `null`, no change |

## Fixture (expected values written before running)

Insert `"car"`, `"cat"`, `"dog"`:

- `contains('car') === true`, `contains('ca') === false` (prefix only), `findOccurrences('ca') === 0`.
- `findPrefix('cab') === null`, `contains('cab') === false`, `findAllWords('cab')` is `[]`.
- After the failed lookups `findAllWords('')` is unchanged and `findPrefix('cab')` is still `null`
(no node was created).
- **Successful call after the failure:** `insert('cab')` → `contains('cab') === true`, count 1.
- **Repeated insertion:** inserting `'car'` again reuses the same node and makes its count 2.

Baseline (`baseline.txt`) matched every expected value; no defect in these paths.

## Proof that the inputs reach the branches

`evidence.mjs` loads an in-memory copy of the real `Trie.js` in which the two `return null`
statements of `findPrefix` also record a hit (the file on disk is not changed). Running the fixture
gives exactly:

- `findPrefix('ca')` → no hit (returns the prefix node);
- `contains('cab')` → hit at **line 76** with `i = 2`, i.e. the missing child is `'b'`;
- `findPrefix(5)` → hit at **line 70** (non-string guard).

## Sensitivity checks (temporary copies only)

| Mutant applied by `check.py` | Named test that passes on the original and fails on the mutant |
| ------------------------------------------------------ | -------------------------------------------------------------- |
| `contains`: drop `&& node.count !== 0` (line 135) | `prefix 'ca' is not a complete word, but 'car' is` |
| `findPrefix`: `return null` → `return node` at line 76 | `missing word 'cab' reaches the null branch of findPrefix` |

The real source is never modified.

## Side observation (not changed)

`remove` only prunes a node when `child.children.constructor === Object`, but `children` is created
with `Object.create(null)` and has no `constructor`, so pruning never runs. Removing `'car'` after
inserting `'car'` and `'cart'` therefore keeps `'cart'` (checked in `baseline.txt`). This leaves
empty nodes behind but returns correct answers, and it is outside this task's scope.

## How to run

From the repository root:

```sh
python3 work/R50-T008/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 Data-Structures/Tree/test/Trie.test.js --reporter=json --outputFile=work/R50-T008/vitest-focused.raw.json` | 7/7 passed |
| Fixture evidence | `node work/R50-T008/evidence.mjs` | 8/8 rows match |
| Mutant: prefix-only node counted as a word (drop count check) | temporary copy | killed by `prefix 'ca' is not a complete word, but 'car' is` |
| Mutant: missing-child branch returns the partial prefix instead of null | temporary copy | killed by `missing word 'cab' reaches the null branch of findPrefix` |
| Repository test script | `npm test -- --reporter=json --outputFile=work/R50-T008/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`.
7 changes: 7 additions & 0 deletions work/R50-T008/baseline.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
contains car/ca/cab/x: true false false false
findPrefix ca is node: true count 0 | findPrefix cab: null
findOccurrences car/ca/cab: 1 0 0
findAllWords cab: [] findAllWords ca: [{"word":"car","count":1},{"word":"cat","count":1}]
after second insert car, occurrences: 2
insert(5): undefined findPrefix(5): null
side check (remove): insert car,cart; remove car -> contains(cart)= true
Loading