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 | * @param {Object<string,any>} obj
|
24 | * @param {function(any,string):any} f
|
25 | */
|
26 | export const forEach = (obj, f) => {
|
27 | for (const key in obj) {
|
28 | f(obj[key], key)
|
29 | }
|
30 | }
|
31 |
|
32 | /**
|
33 | * @template R
|
34 | * @param {Object<string,any>} obj
|
35 | * @param {function(any,string):R} f
|
36 | * @return {Array<R>}
|
37 | */
|
38 | export const map = (obj, f) => {
|
39 | const results = []
|
40 | for (const key in obj) {
|
41 | results.push(f(obj[key], key))
|
42 | }
|
43 | return results
|
44 | }
|
45 |
|
46 | /**
|
47 | * @param {Object<string,any>} obj
|
48 | * @return {number}
|
49 | */
|
50 | export const length = obj => keys(obj).length
|
51 |
|
52 | /**
|
53 | * @param {Object<string,any>} obj
|
54 | * @param {function(any,string):boolean} f
|
55 | * @return {boolean}
|
56 | */
|
57 | export const some = (obj, f) => {
|
58 | for (const key in obj) {
|
59 | if (f(obj[key], key)) {
|
60 | return true
|
61 | }
|
62 | }
|
63 | return false
|
64 | }
|
65 |
|
66 | /**
|
67 | * @param {Object<string,any>} obj
|
68 | * @param {function(any,string):boolean} f
|
69 | * @return {boolean}
|
70 | */
|
71 | export const every = (obj, f) => {
|
72 | for (const key in obj) {
|
73 | if (!f(obj[key], key)) {
|
74 | return false
|
75 | }
|
76 | }
|
77 | return true
|
78 | }
|
79 |
|
80 | /**
|
81 | * Calls `Object.prototype.hasOwnProperty`.
|
82 | *
|
83 | * @param {any} obj
|
84 | * @param {string|symbol} key
|
85 | * @return {boolean}
|
86 | */
|
87 | export const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)
|
88 |
|
89 | /**
|
90 | * @param {Object<string,any>} a
|
91 | * @param {Object<string,any>} b
|
92 | * @return {boolean}
|
93 | */
|
94 | export const equalFlat = (a, b) => a === b || (length(a) === length(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && b[key] === val))
|