-
Notifications
You must be signed in to change notification settings - Fork 4
/
Object.js
65 lines (56 loc) · 1.82 KB
/
Object.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
64
65
// NOTE: all method do not check if the value is a valid object
const objectSet = (object, key, value) => (object[ key ] !== value)
? { ...object, [ key ]: value }
: object
const objectDelete = (object, key) => {
if (!Object.prototype.hasOwnProperty.call(object, key)) return object
const result = { ...object }
delete result[ key ]
return result
}
const objectMerge = (object, mergeObject) => {
for (const [ key, value ] of Object.entries(mergeObject)) { // check if has new data
if (object[ key ] !== value) return { ...object, ...mergeObject }
}
return object
}
const objectMap = (object, mapFunc) => {
const result = {}
for (const [ key, value ] of Object.entries(object)) result[ key ] = mapFunc(value, key)
return result
}
const objectPickKey = (object, keyList) => { // not copy value from prototype
const result = {}
for (const key of keyList) {
if (Object.prototype.hasOwnProperty.call(object, key)) result[ key ] = object[ key ]
}
return result
}
const objectFindKey = (object, findEntryFunc) => {
const entry = Object.entries(object).find(findEntryFunc)
return entry && entry[ 0 ] // return String or undefined
}
const objectFilter = (object, filterFunc) => {
let result
for (const [ key, value ] of Object.entries(object)) { // check if has new data
if (filterFunc(value, key, object)) continue
if (result === undefined) result = { ...object }
delete result[ key ]
}
return result || object
}
const objectFromEntries = (iterable) => { // TODO: NOTE: use `Object.fromEntries` when support to node@>=12.0.0 && chrome@>=73 && firefox@>=63 ?
const result = {}
for (const [ key, value ] of iterable) result[ key ] = value
return result
}
export {
objectSet,
objectDelete,
objectMerge,
objectMap,
objectPickKey,
objectFindKey,
objectFilter,
objectFromEntries
}