Property Based: Find the best properties
const assert = require('assert');
const fc = require('fast-check');
console.log('fast-check ready...');
// none of those algorithms are supposed to be optimized, they are just implementations examples
const average = (a, b) => (a + b) / 2;
fc.assert(
fc.property(
fc.integer(), fc.integer(),
(a, b) => a <= b
? a <= average(a, b) && average(a, b) <= b
: b <= average(a, b) && average(a, b) <= a));
const decompose = (n) => {
for (let v = 2 ; v < Math.sqrt(n) ; ++v)
if (n % v === 0)
return decompose(n/v).concat(v);
return [n];
};
fc.assert(
fc.property(
fc.nat(),
n => decompose(n).reduce((acc, cur) => acc*cur, 1) === n));
const removeDuplicates = data => {
const noDup = [];
for (const c of data)
if (noDup.indexOf(c) === -1)
noDup.push(c);
return noDup;
};
fc.assert(
fc.property(
fc.set(fc.char()),
data => assert.deepEqual(removeDuplicates(data), data)));
const contains = (pattern, text) => text.indexOf(pattern) !== -1;
fc.assert(
fc.property(
fc.string(), fc.string(), fc.string(),
(a, b, c) => contains(b, a + b + c)));
const binaryContains = (e, data) => {
if (data.length === 0) return false;
const mid = Math.floor(data.length/2);
if (data[mid] === e) return true;
return e < data[mid]
? binaryContains(e, data.slice(0, mid))
: binaryContains(e, data.slice(mid+1));
};
const linearContains = (e, data) => data.indexOf(e) !== -1;
fc.assert(
fc.property(
fc.char(), fc.array(fc.char()).map(d => d.sort()),
(c, data) => binaryContains(c, data) === linearContains(c, data)));
const pako = require('pako');
const zip = s => pako.deflate(s, { to: 'string' });
const unzip = s => pako.inflate(s, { to: 'string' });
fc.assert(
fc.property(
fc.string(),
v => unzip(zip(v)) === v));
const math = require('mathjs');
fc.assert(
fc.property(
fc.nat(10000), fc.nat(10000),
(a, b) => math.lcm(a, b) * math.gcd(a, b) === a * b));
no comments