-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
90 lines (72 loc) · 1.87 KB
/
index.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
"use strict";
const { arraysEqual } = require("./arrays-equal");
function isObject(object) {
return object !== null && typeof object === "object";
}
function isFunction(fn) {
return fn instanceof Function;
}
function match(subject, initValue, compareFn) {
return new Matcher(subject, initValue, compareFn);
}
match.EXISTS = Symbol("EXISTS");
class Matcher {
constructor(subject, initValue, compareFn) {
this._subject = subject;
this._result = initValue;
this._compareFn = compareFn || this.compare;
}
get result() {
return this._result;
}
with(pattern, callback) {
if (this._compareFn({ wrapper: this._subject }, { wrapper: pattern })) {
if (callback) {
this._result = callback(this._subject, pattern);
}
return new NoOpMatcher(this._subject, this._result, this._compareFn);
}
return this;
}
compare(subject, pattern) {
for (const [prop, comparison] of Object.entries(pattern)) {
if (Array.isArray(comparison)) {
return arraysEqual(subject[prop], comparison);
} else if (isObject(comparison)) {
if (isObject(subject[prop]) && this._compareFn(subject[prop], comparison)) {
continue;
}
} else if (isFunction(comparison)) {
if (comparison(subject[prop])) {
continue;
}
} else if (comparison === match.EXISTS) {
if (prop in subject) {
continue;
}
} else if (subject[prop] === comparison) {
continue;
}
return false;
}
return true;
}
default(callback) {
if (callback) {
this._result = callback(this._subject, null);
}
return new NoOpMatcher(this._subject, this._result, this._compareFn);
}
}
class NoOpMatcher extends Matcher {
with() {
return this;
}
default() {
return this;
}
}
module.exports = {
match: match,
Matcher: Matcher,
};