picomath/test/_poortf.js

60 lines
2.1 KiB
JavaScript
Raw Normal View History

import assert from 'assert'
import poortf from '../poortf.js'
describe('poortf', () => {
const slate = poortf('slate')
it('creates an empty tf', () => {
assert.throws(() => slate('empty'), TypeError)
assert.throws(() => slate('empty'), /slate.*empty/)
})
const add = poortf('add', [
[args => Array.from(args).every(a => typeof a === 'number'),
(a, b) => a+b],
[args => Array.from(args).every(a => typeof a === 'boolean'),
(p, q) => p || q]
])
it('creates a tf with initial behaviors', () => {
assert.strictEqual(add(2,2), 4)
assert.strictEqual(add(true, false), true)
assert.throws(() => add('kilroy'), TypeError)
})
const defNumber = what => {
slate.addImps([args => typeof args[0] === 'number',
n => 'I am not number ' + (what+n)],
defNumber, what+1)
}
it('extends an empty tf', () => {
defNumber(2)
assert.strictEqual(slate(0, 'was here'), 'I am not number 2')
assert.throws(() => slate('Kilroy', 'was here'), TypeError)
slate.addImps([
[args => typeof args[0] === 'string', s => s + ' wuz here'],
[args => typeof args[0] === 'boolean', () => 'Maybe I am a number']
])
assert.strictEqual(slate('Kilroy', 'was here'), 'Kilroy wuz here')
assert.strictEqual(slate(true), 'Maybe I am a number')
assert.throws(() => slate(['Ha!']), TypeError)
})
it('extends a tf with other behaviors', () => {
add.addImps([args => typeof args[0] === 'string', (s,x) => s + x]),
assert.strictEqual(add('Kilroy', 23), 'Kilroy23')
assert.throws(() => add(['Ha!'], 'gotcha'), TypeError)
})
it('can invalidate and lazily reload implementations', () => {
slate.invalidate(defNumber)
assert.strictEqual(slate.imps.length, 3) // reloader plus two non-number
assert.strictEqual(slate(1), 'I am not number 4') // 'what' is now 3!!
assert.strictEqual(slate('Yorlik', 7), 'Yorlik wuz here')
assert.strictEqual(slate(false), 'Maybe I am a number')
assert.strictEqual(slate.imps.length, 3) // reloader gone
})
})