fast-check
Version:
Property based testing framework for JavaScript (like QuickCheck)
62 lines (61 loc) • 2.32 kB
JavaScript
import { hash } from '../../utils/hash.js';
import { stringify } from '../../utils/stringify.js';
import { cloneMethod, hasCloneMethod } from '../symbols.js';
import { array } from './ArrayArbitrary.js';
import { integer } from './IntegerArbitrary.js';
import { tuple } from './TupleArbitrary.js';
export function func(arb) {
return tuple(array(arb, 1, 10), integer().noShrink()).map(([outs, seed]) => {
const producer = () => {
const recorded = {};
const f = (...args) => {
const repr = stringify(args);
const val = outs[hash(`${seed}${repr}`) % outs.length];
recorded[repr] = val;
return hasCloneMethod(val) ? val[cloneMethod]() : val;
};
return Object.assign(f, {
toString: () => '<function :: ' +
Object.keys(recorded)
.sort()
.map((k) => `${k} => ${stringify(recorded[k])}`)
.join(', ') +
'>',
[cloneMethod]: producer,
});
};
return producer();
});
}
function compareFuncImplem(cmp) {
return tuple(integer().noShrink(), integer(1, 0xffffffff).noShrink()).map(([seed, hashEnvSize]) => {
const producer = () => {
const recorded = {};
const f = (a, b) => {
const reprA = stringify(a);
const reprB = stringify(b);
const hA = hash(`${seed}${reprA}`) % hashEnvSize;
const hB = hash(`${seed}${reprB}`) % hashEnvSize;
const val = cmp(hA, hB);
recorded[`[${reprA},${reprB}]`] = val;
return val;
};
return Object.assign(f, {
toString: () => '<function :: ' +
Object.keys(recorded)
.sort()
.map((k) => `${k} => ${recorded[k]}`)
.join(', ') +
'>',
[cloneMethod]: producer,
});
};
return producer();
});
}
export function compareFunc() {
return compareFuncImplem((hA, hB) => hA - hB);
}
export function compareBooleanFunc() {
return compareFuncImplem((hA, hB) => hA < hB);
}