Skip to content

Instantly share code, notes, and snippets.

@isocroft
Last active July 4, 2024 20:51
Show Gist options
  • Save isocroft/f66e4062eef20beb867dfc2f0a2046d8 to your computer and use it in GitHub Desktop.
Save isocroft/f66e4062eef20beb867dfc2f0a2046d8 to your computer and use it in GitHub Desktop.
A collection of utility functions for mutating and accessing JavaScript objects
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;
};
@isocroft
Copy link
Author

isocroft commented Jul 3, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment