hamjest
Version:
A library of composable matchers for defining meaningful and readable assertions in JavaScript.
42 lines (35 loc) • 979 B
JavaScript
;
const _create = require('lodash/create');
const IsNumber = require('./IsNumber');
const assertThat = require('../assertThat');
const is = require('./Is').is;
const number = require('./IsNumber').number;
function IsCloseTo(threshold, delta) {
assertThat(threshold, is(number()));
assertThat(delta, is(number()));
function getDelta(actual) {
return Math.abs(actual - threshold);
}
return _create(new IsNumber(), {
matchesSafely: function (actual) {
return getDelta(actual) <= delta;
},
describeTo: function (description) {
description
.append('a number within ')
.appendValue(delta)
.append(' of ')
.appendValue(threshold);
},
describeMismatchSafely: function (actual, description) {
description
.appendValue(actual)
.append(' differed by ')
.appendValue(getDelta(actual));
}
});
}
IsCloseTo.closeTo = function (threshold, delta) {
return new IsCloseTo(threshold, delta);
};
module.exports = IsCloseTo;