Today, I decided to have some coding fun and try creating a generic pushUnique
function. This function is designed to check if a new object being added to an array is unique based on a key, and then push it if it meets the criteria.
At this point, all I have is pseudo-code that clearly won't work:
pushUnique<T, U>(arr: T[], obj: T, key: U = null) {
if (key !== null) {
const index = arr.findIndex(o => o.key === obj.key);
}
}
I'm struggling with figuring out how to get the object name of the key and specify it for the findIndex function. Any ideas?
UPDATE:
Thanks to Titian Cernicova-Dragomir's help, here is my improved solution that serves my proof-of-concept needs perfectly!
export class Utils {
pushUnique<T, U>(arr: T[], obj: T, key: (o: T) => U = null, logVerbose: boolean = false): void {
if (logVerbose === true) {
console.log('pushUnique called');
}
if (typeof obj === 'object' && key === null) {
console.warn('Object defined in pushUnique is complex, but a key was not specified.');
} else if (typeof obj !== 'object' && key !== null) {
console.warn('Object is not complex, but a key was specified');
}
const index = key !== null ? arr.findIndex(o => key(o) === key(obj)) : arr.indexOf(obj);
if (index === -1) {
arr.push(obj);
} else {
if (logVerbose === true) {
console.log('Duplicate object, not added');
}
}
}
}