var Decimal = require("decimal.js")
function roundToStep (value, step) {
return new Decimal(value).toNearest(step).toNumber()
}
function roundToStep_natively_and_NAIVELY (value, step) {
return Math.round(value / step) * step;
}
const testCases = [
[15.6, 15.4, 0.4],
[15.2, 15.39, 0.4],
[15.1, 15.12, 0.1],
[1.01, 1.005, 0.01],
];
runTests(roundToStep);
runTests(roundToStep_natively_and_NAIVELY);
function runTests(func) {
console.log(func.name);
const results = [];
testCases.forEach(testCase => {
results.push(test(func, ...testCase));
})
const passed = results.filter(r => r.pass);
const failed = results.filter(r => r.fail);
console.log(`${passed.length} passed, ${failed.length} failed, ${results.length} total`);
failed.forEach(r => console.log(r.msg));
passed.forEach(r => console.log(r.msg));
}
function test(func, expected, ...args) {
const received = func(...args);
const call = `${func.name}(${args.join(",")});`;
if (received === expected) { // not sure if this is the right way to compare floats but ¯\_(ツ)_/¯
return ({ pass: true, msg: `✓ ${call} // got ${received}`});
}
else {
return ({ fail: true, msg: `✘ ${call} // got ${received}, should be ${expected}` });
}
}