-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfindImplementations.js
executable file
·68 lines (59 loc) · 1.6 KB
/
findImplementations.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
function findImplementations(spec, objs) {
return withDefangedDangerousFunctionsCall(function() {
return objs
.map(function(obj) { return findImplementationsFromOneObject(spec, obj); })
.reduce(function(allImpls, impls) { return allImpls.concat(impls); });
});
}
function findImplementationsFromOneObject(spec, obj) {
var objPropertyNames = Object.keys(obj);
var selectedPropertyIndices = repeat(0, spec.operations.length);
var implementations = [];
do {
var candidate = makeCandidate(obj, objPropertyNames, selectedPropertyIndices, spec.operations);
try {
if (spec.test.call(candidate)) {
implementations.push(candidate);
}
} catch (e) { }
} while (increment(selectedPropertyIndices, objPropertyNames.length) == 0);
return implementations;
}
function makeCandidate(obj, objPropertyNames, selectedPropertyIndices, operations) {
var candidate = {};
for (var idx = 0; idx < operations.length; idx++) {
candidate[operations[idx]] = obj[objPropertyNames[selectedPropertyIndices[idx]]];
}
return candidate;
}
// Helpers
function withDefangedDangerousFunctionsCall(f) {
var _alert = global.alert;
global.alert = function() {};
try {
return f();
} finally {
global.alert = _alert;
}
}
function repeat(x, n) {
var ans = [];
while (n-- > 0) {
ans.push(x);
}
return ans;
}
function increment(digits, base) {
var idx = 0;
do {
digits[idx]++;
if (digits[idx] < base) {
return 0;
}
digits[idx] -= base;
idx++;
} while (idx < digits.length);
return 1;
}
// Exports
module.exports = findImplementations;