-
Notifications
You must be signed in to change notification settings - Fork 75
/
has-keypaths.js
52 lines (48 loc) · 1.66 KB
/
has-keypaths.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
/**
* @module 101/has-keypaths
*/
var eql = require('deep-eql');
var keypather = require('keypather')();
var isObject = require('./is-object');
var isBoolean = require('./is-boolean');
var isArray = Array.isArray;
/**
* Determines whether the keypaths exist and have the specified values.
* If obj is not provided findIndex will return a partial-function which accepts a obj as the first argument.
* @function module:101/has-keypaths
* @param {object} [obj] - the object whose properties being checked
* @param {object|array} keypaths - keypaths and values (object) or keypath strings expected to exist on the object (array)
* @param {boolean} [deep] - deep equals when values are specified (objects are recursed),
* deep keypath existance (prototype) when only keys are specified
* @return {boolean|function} Has keypaths or Partial-function function hasKeypaths (which accepts obj)
*/
module.exports = function (obj, keypaths, deep) {
if (arguments.length === 1) {
keypaths = obj;
return function (obj) {
return hasKeypaths(obj, keypaths, deep);
};
}
else {
return hasKeypaths(obj, keypaths, deep);
}
};
function hasKeypaths (obj, keypaths, deep) {
var has = false;
deep = !isBoolean(deep) ? true : deep;
if (isObject(keypaths)) {
has = Object.keys(keypaths).every(function (keypath) {
return deep ?
eql(keypather.get(obj, keypath), keypaths[keypath]) :
keypather.get(obj, keypath) === keypaths[keypath];
});
}
else if (isArray(keypaths)) {
has = keypaths.every(function (keypath) {
return deep ?
keypather.in(obj, keypath) :
keypather.has(obj, keypath);
});
}
return has;
}