-
Notifications
You must be signed in to change notification settings - Fork 13
/
objects.ts
244 lines (210 loc) · 6.77 KB
/
objects.ts
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import { WithoutNil, FilteredResult } from './interfaces';
import { isBooleanLike } from './booleans';
import { get, getTypeOf, isPlainObject } from './deps';
import { DataEntity } from './entities';
import { isArrayLike, isArray } from './arrays';
import { isBuffer } from './buffers';
import { isString, trim } from './strings';
import { toNumber } from './numbers';
import { isPrimitiveValue } from '.';
/**
* Similar to is-plain-object but works better when you cloneDeep a DataEntity
*/
export function isSimpleObject(input: unknown): input is Record<string, unknown> {
if (input == null) return false;
if (isBuffer(input)) return false;
if (isArrayLike(input)) return false;
if (input instanceof Set) return false;
if (input instanceof Map) return false;
return typeof input === 'object';
}
/**
* Get the first value in an object
*/
export function getFirstValue<T>(input: { [key: string]: T }): T | undefined {
return Object.values(input)[0];
}
/**
* Get the first key in an object
*/
export function getFirstKey<T extends object>(input: T): (keyof T) | undefined {
return Object.keys(input)[0] as keyof T;
}
/**
* Verify if the input is a object like type
*/
export function isObjectEntity(input: unknown): boolean {
return DataEntity.isDataEntity(input) || isSimpleObject(input);
}
/**
* A clone deep using `JSON.parse(JSON.stringify(input))`
*/
export function fastCloneDeep<T>(input: T): T {
return JSON.parse(JSON.stringify(input));
}
/** Perform a shallow clone of an object to another, in the fastest way possible */
export function fastAssign<T extends object, U extends object>(target: T, source: U): T & U {
if (!isObjectEntity(source)) {
return target as T & U;
}
for (const [key, val] of Object.entries(source)) {
target[key] = val;
}
return target as T & U;
}
/** Sort keys on an object */
export function sortKeys<T extends Record<string, unknown>>(
input: T,
options: { deep?: boolean } = {}
): T {
const result: Partial<T> = {};
for (const _key of Object.keys(input).sort()) {
const key = _key as keyof T;
const val = input[key];
if (options.deep && isPlainObject(val)) {
result[key] = sortKeys(val as Record<string, unknown>, options) as any;
} else {
result[key] = val;
}
}
return result as T;
}
/** Map the values of an object */
export function mapValues<T extends object, R = T>(
input: T,
fn: (value: T[keyof T], key: (keyof T)) => any
): R {
const result = {} as Partial<R>;
for (const [key, val] of Object.entries(input)) {
result[key] = fn(val, key as keyof T);
}
return result as R;
}
/** Map the keys of an object */
export function mapKeys<T extends object, R = T>(
input: T,
fn: (value: T[keyof T], key: (keyof T)) => any
): R {
const result = {} as Partial<R>;
for (const [key, val] of Object.entries(input)) {
result[fn(val, key as keyof T)] = val;
}
return result as R;
}
/** Build a new object without null or undefined values (shallow) */
export function withoutNil<T>(input: T): WithoutNil<T> {
const result: Partial<WithoutNil<T>> = {};
for (const _key of Object.keys(input as Record<string, any>).sort()) {
const key = _key as keyof T;
if (input[key] != null) {
result[key] = input[key] as any;
}
}
return result as WithoutNil<T>;
}
/**
* Filters the keys of an object, by list of included key and excluded
*/
export function filterObject<
T extends object, I extends(keyof T), E extends (keyof T)
>(data: T, by?: {
includes?: I[];
excludes?: E[];
}): FilteredResult<T, I, E> {
const {
includes = [],
excludes = []
} = by || {};
const result: Partial<FilteredResult<T, I, E>> = {};
Object.keys(data)
.filter((key) => {
const included = includes.length ? includes.includes(key as I) : true;
const excluded = excludes.length ? excludes.includes(key as E) : false;
return included && !excluded;
})
.sort()
.forEach((key) => {
result[key] = data[key];
});
return result as FilteredResult<T, I, E>;
}
/**
* A type safe get function (will always return the correct type)
*
* **IMPORTANT** This does not behave like lodash.get,
* it does not deal with dot notation (nested fields)
* and it will use the default when dealing with OR statements
*/
export function getField<V>(
input: undefined,
field: string,
defaultVal?: V
): V;
export function getField<T, P extends keyof T>(
input: T,
field: P
): T[P];
export function getField<T, P extends keyof T>(
input: T | undefined,
field: P
): T[P];
export function getField<T, P extends keyof T>(
input: T | undefined,
field: P,
defaultVal: never[]
): T[P];
export function getField<T, P extends keyof T, V>(
input: T | undefined,
field: P,
defaultVal: V
): T[P] | V;
export function getField<T, P extends keyof T, V extends T[P]>(
input: T | undefined,
field: P, defaultVal: V
): T[P];
export function getField<T, P extends keyof T, V>(
input: T,
field: P,
defaultVal?: V
): any {
const result = get(input, field);
if (isBooleanLike(defaultVal)) {
if (result == null) return defaultVal;
return result;
}
return result || defaultVal;
}
/**
* Check if a object has property (and not included in the prototype)
* Different from has since it doesn't deal with dot notation values.
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export function hasOwn(obj: any, prop: string|symbol|number): boolean {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
export function lookup(input: unknown): (key: unknown) => any {
// lookup entity can be a string, object or array
if (!isObjectEntity(input) && !isString(input) && !isArray(input)) {
throw Error(`input must be an Object Entity, String, received ${getTypeOf(input)}`);
}
return function _lookup(key: unknown) {
if (key == null) return null;
// This may be too restrictive at some point
if (!isPrimitiveValue(key)) {
throw Error(`lookup key must be not be an object, received ${getTypeOf(key)}`);
}
if (isString(input)) {
return _lookupStringToObject(input)[key as string];
}
if (isArray(input)) return input[toNumber(key)];
const lookupObj = input as Record<string, unknown>;
return lookupObj[key as string];
};
}
function _lookupStringToObject(stringInput: string): Record<string, string> {
return stringInput.split('\n').reduce((asObj, line) => {
const [k, v] = trim(line).split(':', 2);
asObj[trim(k)] = trim(v);
return asObj;
}, {});
}