-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexcept.js
More file actions
72 lines (62 loc) · 2.38 KB
/
except.js
File metadata and controls
72 lines (62 loc) · 2.38 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
;(function() {
/**
* It returns a new object with the keys that were passed to the function removed
* @param args Can be an array of keys or strings[keys] to be removed from the object.
* @returns an object with the keys that were not passed in the arguments.
*
* Examples:
*
* ```js
*
const obj1 = { name: "foo", age: 20, city: "bar" }
console.log(obj1.except('name'))
// output: { age: 20, city: "bar" }
console.log(obj1.except(['name']))
// output: { age: 20, city: "bar" }
console.log(obj1.except('name', 'age'))
// output: { city: 'bar' }
console.log(obj1.except(['name', 'age']))
// output: { city: 'bar' }
const user = { name: "John Smith", age: 45, email: "john.smith@gmail.com", password: "password"}
console.log(user.except('password'))
// output: { name: "John Smith", age: 45, email: "john.smith@gmail.com" }
* ```
*/
function except (args) {
const values = this
const result = {...values}
const keys = Object?.keys(values)
if(arguments.length) {
for(let arg in arguments) {
if(arg != "except") {
if(typeof arguments[arg] == 'string') {
keys.forEach(key => {
if(key == arguments[arg]) {
delete result[key]
}
})
}
else if(typeof arguments[arg] == 'object') {
if(arguments[arg][0]) {
arguments[arg].forEach((keyItem) => {
keys.forEach(key => {
if(key == keyItem) {
delete result[key]
}
})
})
}
else {
throw new Error('except() expects only arrays or strings')
}
}
else {
throw new Error('except() expects only arrays or strings')
}
}
}
}
return result
}
Object.prototype.except = except
})()