Last active
July 4, 2024 20:51
-
-
Save isocroft/f66e4062eef20beb867dfc2f0a2046d8 to your computer and use it in GitHub Desktop.
A collection of utility functions for mutating and accessing JavaScript objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Literal = unknown | |
export interface ReducableObject { | |
[key:string]: Literal | ReducableObject; | |
} | |
export function throttleFilterCallbackRoutine<S, N extends () => void> ( | |
routine: (...args: [S]) => N, | |
routineArgs: [S], | |
interval = 500 | |
) { | |
let shouldFire = true; | |
return function callback() { | |
if (shouldFire) { | |
const result = routine.call(null, ...routineArgs); | |
shouldFire = false; | |
setTimeout(() => { | |
shouldFire = true; | |
}, interval); | |
return result; | |
} | |
return (() => undefined) as N; | |
}; | |
}; | |
export function extractPropertyValue<O extends ReducableObject> ( | |
objectProperty = "", | |
object = {} as O, | |
delimeter = "." | |
) { | |
const value = objectProperty.includes(delimeter) | |
/* @ts-ignore */ | |
? objectProperty.split(delimeter).reduce<O>((subObject, prop) => { | |
const result = typeof subObject === "object" ? subObject[prop] : subObject; | |
return result; | |
}, object) | |
: object[objectProperty]; | |
return value; | |
} | |
export function toUniqueItemList<T extends {}> ( | |
initialList: T[] = [], | |
propertyKey = "" | |
) { | |
let initialListCounter, | |
innerLoopCounter, | |
finalListItem, | |
initialListItem; | |
const finalList: T[] = []; | |
resetLabel: for ( | |
initialListCounter = 0; | |
initialListCounter < initialList.length; | |
++initialListCounter | |
) { | |
for ( | |
innerLoopCounter = 0; | |
innerLoopCounter < finalList.length; | |
++innerLoopCounter | |
) { | |
finalListItem = finalList[innerLoopCounter]; | |
finalListItem = | |
propertyKey !== "" && typeof finalListItem !== "string" | |
? extractPropertyValue<T>(propertyKey, finalListItem) | |
: finalListItem; | |
initialListItem = initialList[initialListCounter]; | |
initialListItem = | |
propertyKey !== "" && typeof initialListItem !== "string" | |
? extractPropertyValue<T>(propertyKey, initialListItem) | |
: initialListItem; | |
if (finalListItem === initialListItem) continue resetLabel; | |
} | |
finalList.push(initialList[initialListCounter]); | |
} | |
return finalList; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
LIVE DEMO: https://codesandbox.io/s/filter-component-stage-7-62d31p