-
Notifications
You must be signed in to change notification settings - Fork 116
/
Copy pathunderscore.comparison.islike.js
67 lines (57 loc) · 2.21 KB
/
underscore.comparison.islike.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
/*
* Tests if an object is like another. This means objects should follow the same
* structure and arrays should contain the same types.
*
* E.g.
*
* _.islike(
* {name: "James", age: 10, hobbies: ["football", "computer games", "baking"]},
* {name: "", age: 0, hobbies: [""]}
* )
*/
(function() {
// Establish the root object, `window` in the browser, or `require` it on the server.
if (typeof exports === 'object') {
_ = module.exports = require('underscore');
}
var islike = function(obj, pattern) {
if (typeof pattern === "function") {
return obj instanceof pattern;
}
if (typeof obj !== typeof pattern) return false;
if (_.isArray(pattern) && !_.isArray(obj)) return false;
var type = typeof pattern;
if (type == "object") {
if (pattern instanceof Array) {
if (pattern.length > 0) {
var oTypes = _.uniq(_.map(obj, fTypeof));
var pTypes = _.uniq(_.map(pattern, fTypeof));
if (_.difference(oTypes, pTypes).length) {
return false;
}
}
} else { // object
if (pattern.constructor === pattern.constructor.prototype.constructor) {
// for 'simple' objects we enumerate
var anyUnlike = _.any(pattern, function(p, k) {
var o = obj[k];
return !islike(o, p);
});
if (anyUnlike) {
return false;
}
} else {
// for 'types' we just check the inheritance chain
if (!(obj instanceof pattern.constructor)) {
return false;
}
}
}
}
return true;
};
var fTypeof = function(o) {
return typeof o;
};
_.mixin({islike: islike});
}).call(this);