Jasmine toBeCloseTo() matcher

Today I was faced with a problem of checking that a number was really close to another number, but not necessarily equal to it. Jasmine has a really nifty matcher toBeCloseTo() just for this case. See the code below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
getJasmineRequireObj().toBeCloseTo = function() {

    function toBeCloseTo() {
        return {
            compare: function(actual, expected, precision) {
                if (precision !== 0) {
                    precision = precision || 2;
                }

                return {
                    pass: Math.abs(expected - actual) < (Math.pow(10, -precision) / 2)
                };
            }
        };
    }

    return toBeCloseTo;
};