1 | /**
|
2 | * Utility functions for working with EcmaScript objects.
|
3 | *
|
4 | * @module object
|
5 | */
|
6 |
|
7 | /**
|
8 | * @return {Object<string,any>} obj
|
9 | */
|
10 | export const create = () => Object.create(null)
|
11 |
|
12 | /**
|
13 | * Object.assign
|
14 | */
|
15 | export const assign = Object.assign
|
16 |
|
17 | /**
|
18 | * @param {Object<string,any>} obj
|
19 | */
|
20 | export const keys = Object.keys
|
21 |
|
22 | /**
|
23 | * @template V
|
24 | * @param {{[k:string]:V}} obj
|
25 | * @param {function(V,string):any} f
|
26 | */
|
27 | export const forEach = (obj, f) => {
|
28 | for (const key in obj) {
|
29 | f(obj[key], key)
|
30 | }
|
31 | }
|
32 |
|
33 | /**
|
34 | * @todo implement mapToArray & map
|
35 | *
|
36 | * @template R
|
37 | * @param {Object<string,any>} obj
|
38 | * @param {function(any,string):R} f
|
39 | * @return {Array<R>}
|
40 | */
|
41 | export const map = (obj, f) => {
|
42 | const results = []
|
43 | for (const key in obj) {
|
44 | results.push(f(obj[key], key))
|
45 | }
|
46 | return results
|
47 | }
|
48 |
|
49 | /**
|
50 | * @param {Object<string,any>} obj
|
51 | * @return {number}
|
52 | */
|
53 | export const length = obj => keys(obj).length
|
54 |
|
55 | /**
|
56 | * @param {Object<string,any>} obj
|
57 | * @param {function(any,string):boolean} f
|
58 | * @return {boolean}
|
59 | */
|
60 | export const some = (obj, f) => {
|
61 | for (const key in obj) {
|
62 | if (f(obj[key], key)) {
|
63 | return true
|
64 | }
|
65 | }
|
66 | return false
|
67 | }
|
68 |
|
69 | /**
|
70 | * @param {Object|undefined} obj
|
71 | */
|
72 | export const isEmpty = obj => {
|
73 | // eslint-disable-next-line
|
74 | for (const _k in obj) {
|
75 | return false
|
76 | }
|
77 | return true
|
78 | }
|
79 |
|
80 | /**
|
81 | * @param {Object<string,any>} obj
|
82 | * @param {function(any,string):boolean} f
|
83 | * @return {boolean}
|
84 | */
|
85 | export const every = (obj, f) => {
|
86 | for (const key in obj) {
|
87 | if (!f(obj[key], key)) {
|
88 | return false
|
89 | }
|
90 | }
|
91 | return true
|
92 | }
|
93 |
|
94 | /**
|
95 | * Calls `Object.prototype.hasOwnProperty`.
|
96 | *
|
97 | * @param {any} obj
|
98 | * @param {string|symbol} key
|
99 | * @return {boolean}
|
100 | */
|
101 | export const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)
|
102 |
|
103 | /**
|
104 | * @param {Object<string,any>} a
|
105 | * @param {Object<string,any>} b
|
106 | * @return {boolean}
|
107 | */
|
108 | export const equalFlat = (a, b) => a === b || (length(a) === length(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && b[key] === val))
|