Skip to content

Instantly share code, notes, and snippets.

@adriangabardo
Last active August 23, 2023 06:50
Show Gist options
  • Save adriangabardo/72751ba2e132ef158e746bf39cab363c to your computer and use it in GitHub Desktop.
Save adriangabardo/72751ba2e132ef158e746bf39cab363c to your computer and use it in GitHub Desktop.
Inject extra properties into a native interface
// Defining a searchBy method on an array
interface SearchFn<T> {
(key: string, value: string): { index: number; value: T }[] | undefined;
}
// Extend the Array interface to include a searchBy method
interface SearchableArray<T> extends Array<T> {
searchBy: SearchFn<T>;
}
// Inject the searchBy method into an array
const injectSearch = <T>(array: T[]): SearchableArray<T> => {
Object.defineProperties(array, {
searchBy: {
value: function (this: T[], key: string, value: string) {
return this.reduce(
(previous, current: any, index) => {
if (current && current[key] && current[key] === value) {
previous.push({ index, value: current });
}
return previous;
},
[] as { index: number; value: T }[],
);
} as SearchFn<T>,
},
});
return array as SearchableArray<T>;
};
// Definition of a Person object
interface Person {
firstName: string;
lastName: string;
age: number;
}
// Creating an array of people that can be searched
const people = injectSearch<Person>([]);
people.push({
age: 20,
firstName: 'John',
lastName: 'Doe',
});
people.push({
age: 75,
firstName: 'Jane',
lastName: 'Doe',
});
const john = people.searchBy('firstName', 'John');
console.log('John:', john);
const jane = people.searchBy('firstName', 'Jane');
console.log('Jane:', jane);
const all = people.searchBy('lastName', 'Doe');
console.log('All:', all);
/**
John: [
{ index: 0, value: { age: 20, firstName: 'John', lastName: 'Doe' } }
]
Jane: [
{ index: 1, value: { age: 75, firstName: 'Jane', lastName: 'Doe' } }
]
All: [
{ index: 0, value: { age: 20, firstName: 'John', lastName: 'Doe' } },
{ index: 1, value: { age: 75, firstName: 'Jane', lastName: 'Doe' } }
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment