-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.js
49 lines (41 loc) · 1.09 KB
/
index.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
/*!
* unset-value <https://github.com/jonschlinkert/unset-value>
*
* Copyright (c) 2015, 2017, Jon Schlinkert.
* Released under the MIT License.
*/
'use strict';
var isObject = require('isobject');
var has = require('has-value');
const isUnsafeKey = key => {
return key === '__proto__' || key === 'constructor' || key === 'prototype';
};
const validateKey = key => {
if (isUnsafeKey(key)) {
throw new Error(`Cannot set unsafe key: "${key}"`);
}
};
module.exports = function unset(obj, prop) {
if (!isObject(obj)) {
throw new TypeError('expected an object.');
}
var isArray = Array.isArray(prop);
if (!isArray && obj.hasOwnProperty(prop)) {
delete obj[prop];
return true;
}
if (has(obj, prop)) {
var segs = isArray ? prop.slice() : prop.split('.');
var last = segs.pop();
while (segs.length && segs[segs.length - 1].slice(-1) === '\\') {
last = segs.pop().slice(0, -1) + '.' + last;
}
while (segs.length) {
prop = segs.shift();
validateKey(prop);
obj = obj[prop];
}
return (delete obj[last]);
}
return true;
};