-
Notifications
You must be signed in to change notification settings - Fork 75
/
set.js
63 lines (59 loc) · 1.68 KB
/
set.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
/**
* @module 101/set
*/
var isString = require('./is-string');
var isNumber = require('./is-number');
var isObject = require('./is-object');
var keypather = require('keypather')();
/**
* Functional version of obj[key] = val.
* When only a key and val are specified set returns a partial-function which accepts obj.
* @function module:101/set
* @param {*} [obj] - object on which the values will be set
* @param {string} key - key of the value being set on obj
* @param {*} val - value of the key being set on obj
* @return {*|function} The same obj with new value set or Partial-function set (which accepts obj) and returns the same obj with val set
*/
module.exports = set;
function set (obj, key, val) {
var setObj;
if (arguments.length === 1) {
// (setObj)
setObj = obj;
return function (obj) {
return setKeypaths(obj, setObj); // extends original
};
}
if (arguments.length === 2) {
if (isString(obj) || isNumber(obj)) {
// (key, val)
val = key;
key = obj;
setObj = {};
keypather.set(setObj, key, val);
return function (obj) {
return setKeypaths(obj, setObj); // extends original
};
}
else if (isObject(key)) {
// (obj, setObj)
setObj = key;
return setKeypaths(obj, setObj); // extends original
}
else {
throw new TypeError('Invalid arguments: expected string, number, or object');
}
}
else {
setObj = {};
setObj[key] = val
return setKeypaths(obj, setObj); // extends original
}
}
function setKeypaths (obj, setObj) {
Object.keys(setObj).forEach(function (keypath) {
var val = setObj[keypath];
keypather.set(obj, keypath, val);
});
return obj;
}