2021-12-17 11:58:15 +01:00
|
|
|
function pick <O extends object, K extends keyof O> (object: O, keys: K[]): Pick<O, K> {
|
|
|
|
const result: any = {}
|
|
|
|
|
|
|
|
for (const key of keys) {
|
|
|
|
if (Object.prototype.hasOwnProperty.call(object, key)) {
|
|
|
|
result[key] = object[key]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
2022-08-17 15:25:58 +02:00
|
|
|
function omit <O extends object, K extends keyof O> (object: O, keys: K[]): Exclude<O, K> {
|
|
|
|
const result: any = {}
|
|
|
|
const keysSet = new Set(keys) as Set<string>
|
|
|
|
|
|
|
|
for (const [ key, value ] of Object.entries(object)) {
|
|
|
|
if (keysSet.has(key)) continue
|
|
|
|
|
|
|
|
result[key] = value
|
|
|
|
}
|
|
|
|
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
2023-05-24 16:48:54 +02:00
|
|
|
function objectKeysTyped <O extends object, K extends keyof O> (object: O): K[] {
|
|
|
|
return (Object.keys(object) as K[])
|
|
|
|
}
|
|
|
|
|
2021-12-29 14:44:58 +01:00
|
|
|
function getKeys <O extends object, K extends keyof O> (object: O, keys: K[]): K[] {
|
|
|
|
return (Object.keys(object) as K[]).filter(k => keys.includes(k))
|
|
|
|
}
|
|
|
|
|
2023-05-24 16:48:54 +02:00
|
|
|
function hasKey <T extends object> (obj: T, k: keyof any): k is keyof T {
|
|
|
|
return k in obj
|
|
|
|
}
|
|
|
|
|
2021-12-17 11:58:15 +01:00
|
|
|
function sortObjectComparator (key: string, order: 'asc' | 'desc') {
|
|
|
|
return (a: any, b: any) => {
|
|
|
|
if (a[key] < b[key]) {
|
|
|
|
return order === 'asc' ? -1 : 1
|
|
|
|
}
|
|
|
|
|
|
|
|
if (a[key] > b[key]) {
|
|
|
|
return order === 'asc' ? 1 : -1
|
|
|
|
}
|
|
|
|
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-06 11:39:23 +01:00
|
|
|
function shallowCopy <T> (o: T): T {
|
|
|
|
return Object.assign(Object.create(Object.getPrototypeOf(o)), o)
|
|
|
|
}
|
|
|
|
|
2023-04-14 09:57:37 +02:00
|
|
|
function simpleObjectsDeepEqual (a: any, b: any) {
|
|
|
|
if (a === b) return true
|
|
|
|
|
|
|
|
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
const keysA = Object.keys(a)
|
|
|
|
const keysB = Object.keys(b)
|
|
|
|
|
|
|
|
if (keysA.length !== keysB.length) return false
|
|
|
|
|
|
|
|
for (const key of keysA) {
|
|
|
|
if (!keysB.includes(key)) return false
|
|
|
|
|
|
|
|
if (!simpleObjectsDeepEqual(a[key], b[key])) return false
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2021-12-17 11:58:15 +01:00
|
|
|
export {
|
|
|
|
pick,
|
2022-08-17 15:25:58 +02:00
|
|
|
omit,
|
2023-05-24 16:48:54 +02:00
|
|
|
objectKeysTyped,
|
2021-12-29 14:44:58 +01:00
|
|
|
getKeys,
|
2023-05-24 16:48:54 +02:00
|
|
|
hasKey,
|
2023-03-06 11:39:23 +01:00
|
|
|
shallowCopy,
|
2023-04-14 09:57:37 +02:00
|
|
|
sortObjectComparator,
|
|
|
|
simpleObjectsDeepEqual
|
2021-12-17 11:58:15 +01:00
|
|
|
}
|