-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
77 lines (61 loc) · 2.44 KB
/
index.js
File metadata and controls
77 lines (61 loc) · 2.44 KB
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
/**
* Sets value in object according to provided path
* @param {Object} context
* @param {Array|string} path
* @param {*} value
* @param {Boolean} push If set to true and last object in path is Array value is pushed to the array
* @return {Object} Copy of object with new value set
*/
function createSetIn(mutable) {
return function setIn(context, path, value, push) {
if(typeof path === 'undefined' || path === null) {
throw new Error('Path is undefined');
}
const pathType = Object.prototype.toString.call(path);
if(pathType !== '[object Undefined]' && pathType !== '[object Array]') {
path = [path];
}
else {
path = [].concat(path);
}
var currentPathPart = path.shift();
if(typeof currentPathPart === 'undefined' || currentPathPart === null) {
throw new Error('Path part is undefined');
}
if(!context) {
context = {};
}
var currentValue = path.length === 0 ? value : setIn(context[currentPathPart], path, value, push);
var contextType = Object.prototype.toString.call(context);
if(contextType === '[object Array]') {
var copy = mutable ? context : [].concat(context);
copy[currentPathPart] = currentValue;
return copy;
}
else if(contextType === '[object Object]') {
var copy = mutable ? context : {};
if(push && path.length === 0) {
contextType = Object.prototype.toString.call(context[currentPathPart]);
if(contextType !== '[object Array]' && contextType !== '[object Undefined]') {
throw new Error('Cannot push to ' + contextType);
}
if(contextType === '[object Undefined]') {
copy[currentPathPart] = [];
}
else {
copy[currentPathPart] = mutable ? context[currentPathPart] : [].concat(context[currentPathPart]);
}
copy[currentPathPart].push(value);
}
else {
copy[currentPathPart] = currentValue;
}
return mutable ? context : Object.assign({}, context, copy);
}
else {
throw new Error('Trying to add property to ' + contextType);
}
};
}
module.exports = createSetIn();
module.exports.mutableSetIn = createSetIn(true);