Skip to content

Commit da10b23

Browse files
committed
add toCloseTo2DArray custom matcher
1 parent 4d8eeb4 commit da10b23

File tree

1 file changed

+56
-4
lines changed

1 file changed

+56
-4
lines changed

test/jasmine/assets/custom_matchers.js

Lines changed: 56 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,7 @@ module.exports = {
44
toBeCloseToArray: function() {
55
return {
66
compare: function(actual, expected, precision) {
7-
if(precision !== 0) {
8-
precision = Math.pow(10, -precision) / 2 || 0.005;
9-
}
7+
precision = coercePosition(precision);
108

119
var tested = actual.map(function(element, i) {
1210
return Math.abs(expected[i] - element) < precision;
@@ -23,5 +21,59 @@ module.exports = {
2321
};
2422
}
2523
};
26-
}
24+
},
25+
26+
// toBeCloseTo... but for 2D arrays
27+
toBeCloseTo2DArray: function() {
28+
return {
29+
compare: function(actual, expected, precision) {
30+
precision = coercePosition(precision);
31+
32+
var passed = true;
33+
34+
if(expected.length !== actual.length) passed = false;
35+
else {
36+
for(var i = 0; i < expected.length; ++i) {
37+
if(expected[i].length !== actual[i].length) {
38+
passed = false;
39+
break;
40+
}
41+
42+
for(var j = 0; j < expected[i].length; ++j) {
43+
var isClose = Math.abs(expected[i][j] - actual[i][j]) < precision;
44+
45+
if(!isClose) {
46+
passed = false;
47+
break;
48+
}
49+
}
50+
}
51+
}
52+
53+
var message = [
54+
'Expected',
55+
arrayToStr(actual.map(arrayToStr)),
56+
'to be close to',
57+
arrayToStr(expected.map(arrayToStr))
58+
].join(' ');
59+
60+
return {
61+
pass: passed,
62+
message: message
63+
};
64+
}
65+
};
66+
},
2767
};
68+
69+
function coercePosition(precision) {
70+
if(precision !== 0) {
71+
precision = Math.pow(10, -precision) / 2 || 0.005;
72+
}
73+
74+
return precision;
75+
}
76+
77+
function arrayToStr(array) {
78+
return '[ ' + array.join(', ') + ' ]';
79+
}

0 commit comments

Comments
 (0)