-
Notifications
You must be signed in to change notification settings - Fork 75
/
del.js
54 lines (49 loc) · 1.33 KB
/
del.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
/**
* @module 101/del
*/
var keypather = require('keypather')();
var passAny = require('./pass-any');
var isString = require('./is-string');
var isNumber = require('./is-number');
var isObject = require('./is-object');
/**
* Functional version of delete obj[key].
* When only a key is specified del returns a partial-function which accepts obj.
* @function module:101/del
* @param {*} [obj] - object on which the values will be del
* @param {string} key - key of the value being del on obj
* @return {*|function} The same obj without the deleted key or Partial-function del (which accepts obj) and returns the same obj without the deleted key.
*/
module.exports = del;
function del (obj, key) {
if (arguments.length === 1) {
// (key)
key = obj;
return function (obj) {
return _del(obj, key);
};
}
else {
return _del(obj, key);
}
}
function _del (obj, key) {
var keys;
var numberOrString = passAny(isString, isNumber);
if (isObject(obj) && numberOrString(key)) {
// (obj, key)
keypather.del(obj, key);
return obj;
}
else if (isObject(obj) && Array.isArray(key)) {
// (obj, keys)
keys = key;
for (var i = 0; i < keys.length; i++) {
keypather.del(obj, keys[i]);
}
return obj;
}
else {
throw new TypeError('Invalid arguments: expected str, val or val, obj');
}
}