feat(js): m01 util and m02 model with tests, fixtures, purity audit
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
5be3cebe71
commit
22c221a042
+5
-4
@@ -8,11 +8,12 @@ const here = dirname(fileURLToPath(import.meta.url))
|
||||
export const loadFixture = (name) =>
|
||||
JSON.parse(readFileSync(join(here, '..', '..', 'fixtures', `${name}.json`), 'utf8'))
|
||||
|
||||
/** Deep-freeze for tests (independent of the student's deepFreeze). */
|
||||
export const freeze = (x) => {
|
||||
if (x !== null && typeof x === 'object' && !Object.isFrozen(x)) {
|
||||
/** Deep-freeze for tests (independent of the student's deepFreeze). Recurses into children even of already-frozen objects. */
|
||||
export const freeze = (x, seen = new WeakSet()) => {
|
||||
if (x !== null && typeof x === 'object' && !seen.has(x)) {
|
||||
seen.add(x)
|
||||
Object.freeze(x)
|
||||
Object.values(x).forEach(freeze)
|
||||
Object.values(x).forEach((v) => freeze(v, seen))
|
||||
}
|
||||
return x
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { range, dropLast, contains, pipe, compose, deepFreeze } from '../src/util.js'
|
||||
import { freeze } from './helpers.js'
|
||||
|
||||
test('m01 range(0) is empty', () => assert.deepEqual(range(0), []))
|
||||
test('m01 range(3) counts from zero up to n-1', () => assert.deepEqual(range(3), [0, 1, 2]))
|
||||
|
||||
test('m01 dropLast of an empty list is empty', () => assert.deepEqual(dropLast([]), []))
|
||||
test('m01 dropLast removes only the last element', () => assert.deepEqual(dropLast([1, 2, 3]), [1, 2]))
|
||||
test('m01 dropLast leaves its input untouched', () => {
|
||||
const xs = freeze([1, 2, 3])
|
||||
assert.deepEqual(dropLast(xs), [1, 2])
|
||||
assert.deepEqual(xs, [1, 2, 3])
|
||||
})
|
||||
|
||||
const sameParity = (a, b) => a % 2 === b % 2
|
||||
test('m01 contains finds an element using the supplied equality', () =>
|
||||
assert.equal(contains([1, 2, 3], 5, sameParity), true))
|
||||
test('m01 contains is false when no element is equal', () =>
|
||||
assert.equal(contains([2, 4], 3, sameParity), false))
|
||||
test('m01 contains is false for an empty list', () =>
|
||||
assert.equal(contains([], 1, (a, b) => a === b), false))
|
||||
test('m01 contains compares structurally when given a structural equality', () => {
|
||||
const eq = (a, b) => a.x === b.x && a.y === b.y
|
||||
assert.equal(contains(freeze([{ x: 1, y: 2 }]), { x: 1, y: 2 }, eq), true)
|
||||
})
|
||||
|
||||
test('m01 pipe threads a value through functions left to right', () =>
|
||||
assert.equal(pipe(2, (x) => x + 1, (x) => x * 10), 30))
|
||||
test('m01 pipe with no functions returns the value', () => assert.equal(pipe(5), 5))
|
||||
|
||||
test('m01 compose applies functions right to left', () =>
|
||||
assert.equal(compose((x) => x * 10, (x) => x + 1)(2), 30))
|
||||
test('m01 compose with no functions is the identity', () => assert.equal(compose()(5), 5))
|
||||
|
||||
test('m01 deepFreeze freezes nested objects and arrays', () => {
|
||||
const o = deepFreeze({ a: { b: [1, { c: 2 }] } })
|
||||
assert.ok(Object.isFrozen(o))
|
||||
assert.ok(Object.isFrozen(o.a))
|
||||
assert.ok(Object.isFrozen(o.a.b))
|
||||
assert.ok(Object.isFrozen(o.a.b[1]))
|
||||
})
|
||||
test('m01 deepFreeze returns the same object it was given', () => {
|
||||
const o = {}
|
||||
assert.equal(deepFreeze(o), o)
|
||||
})
|
||||
@@ -0,0 +1,29 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { point, pointEquals, delta, opposite, Action, initialState } from '../src/model.js'
|
||||
import { loadFixture, freeze } from './helpers.js'
|
||||
|
||||
const fixtureTests = (name, f) => {
|
||||
const fx = loadFixture(name)
|
||||
fx.cases.forEach((c) =>
|
||||
test(`m02 ${fx.function}: ${c.name}`, () => assert.deepStrictEqual(f(...freeze(c.args)), c.expected)))
|
||||
}
|
||||
|
||||
fixtureTests('m02-delta', delta)
|
||||
fixtureTests('m02-opposite', opposite)
|
||||
fixtureTests('m02-point-equals', pointEquals)
|
||||
fixtureTests('m02-initial-state', initialState)
|
||||
|
||||
test('m02 point builds a {x, y} record', () => assert.deepStrictEqual(point(3, 4), { x: 3, y: 4 }))
|
||||
|
||||
test('m02 opposite is its own inverse', () =>
|
||||
['Up', 'Down', 'Left', 'Right'].forEach((d) => assert.equal(opposite(opposite(d)), d)))
|
||||
|
||||
test('m02 Action constants are tagged records', () => {
|
||||
assert.deepStrictEqual(Action.Tick, { tag: 'Tick' })
|
||||
assert.deepStrictEqual(Action.TogglePause, { tag: 'TogglePause' })
|
||||
assert.deepStrictEqual(Action.Restart, { tag: 'Restart' })
|
||||
assert.deepStrictEqual(Action.Frame, { tag: 'Frame' })
|
||||
})
|
||||
test('m02 Action.Turn carries the direction', () =>
|
||||
assert.deepStrictEqual(Action.Turn('Left'), { tag: 'Turn', dir: 'Left' }))
|
||||
@@ -0,0 +1,75 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readdirSync, readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join, basename } from 'node:path'
|
||||
|
||||
const srcDir = join(dirname(fileURLToPath(import.meta.url)), '..', 'src')
|
||||
|
||||
// Files that are allowed to touch the outside world.
|
||||
const excluded = (file) => ['runtime.js', 'browser.js', 'main.js'].includes(basename(file))
|
||||
|
||||
const banned = [
|
||||
['let', /\blet\b/],
|
||||
['var', /\bvar\b/],
|
||||
['++', /\+\+/],
|
||||
['--', /--/],
|
||||
['.push(', /\.push\(/],
|
||||
['.pop(', /\.pop\(/],
|
||||
['.shift(', /\.shift\(/],
|
||||
['.unshift(', /\.unshift\(/],
|
||||
['.splice(', /\.splice\(/],
|
||||
['.sort(', /\.sort\(/],
|
||||
['.reverse(', /\.reverse\(/],
|
||||
['Math.random', /\bMath\.random\b/],
|
||||
['Date.now', /\bDate\.now\b/],
|
||||
['performance.now', /\bperformance\.now\b/],
|
||||
['document', /\bdocument\b/],
|
||||
['window', /\bwindow\b/],
|
||||
['addEventListener', /\baddEventListener\b/],
|
||||
]
|
||||
|
||||
const stripComments = (code) => code.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '')
|
||||
const violations = (code) => banned.filter(([, re]) => re.test(stripComments(code))).map(([name]) => name)
|
||||
|
||||
const jsFiles = (dir) =>
|
||||
readdirSync(dir, { withFileTypes: true }).flatMap((e) =>
|
||||
e.isDirectory() ? jsFiles(join(dir, e.name)) : e.name.endsWith('.js') ? [join(dir, e.name)] : [])
|
||||
|
||||
banned.forEach(([name]) =>
|
||||
test(`purity scanner flags a known-bad sample using ${name}`, () => {
|
||||
const samples = {
|
||||
let: 'let n = 0',
|
||||
var: 'var n = 0',
|
||||
'++': 'n++',
|
||||
'--': 'n--',
|
||||
'.push(': 'xs.push(1)',
|
||||
'.pop(': 'xs.pop()',
|
||||
'.shift(': 'xs.shift()',
|
||||
'.unshift(': 'xs.unshift(1)',
|
||||
'.splice(': 'xs.splice(0, 1)',
|
||||
'.sort(': 'xs.sort()',
|
||||
'.reverse(': 'xs.reverse()',
|
||||
'Math.random': 'const r = Math.random()',
|
||||
'Date.now': 'const t = Date.now()',
|
||||
'performance.now': 'const t = performance.now()',
|
||||
document: 'document.title',
|
||||
window: 'window.alert(1)',
|
||||
addEventListener: 'x.addEventListener("click", f)',
|
||||
}
|
||||
assert.ok(violations(samples[name]).includes(name))
|
||||
}))
|
||||
|
||||
test('purity scanner ignores banned words inside comments', () => {
|
||||
const code = '// let var Math.random()\n/* xs.push(1); document; n++ */\nconst a = 1 // window\n'
|
||||
assert.deepEqual(violations(code), [])
|
||||
})
|
||||
|
||||
test('purity scanner accepts ordinary pure code', () =>
|
||||
assert.deepEqual(violations('export const f = (xs) => xs.map((x) => x + 1)'), []))
|
||||
|
||||
jsFiles(srcDir)
|
||||
.filter((f) => !excluded(f))
|
||||
.forEach((f) =>
|
||||
test(`purity: ${f.slice(srcDir.length + 1)} has no banned constructs`, () =>
|
||||
assert.deepEqual(violations(readFileSync(f, 'utf8')), [])))
|
||||
Reference in New Issue
Block a user