Skip to content

Instantly share code, notes, and snippets.

@fearthecowboy
Last active June 25, 2020 00:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fearthecowboy/c7d979dd624011336576458c35083dd4 to your computer and use it in GitHub Desktop.
Save fearthecowboy/c7d979dd624011336576458c35083dd4 to your computer and use it in GitHub Desktop.
Object.defineProperties(Array.prototype, {
where: { value: Array.prototype.filter },
select: { value: Array.prototype.map },
any: { value: Array.prototype.some },
all: { value: Array.prototype.every },
insert: { value: function (position: number, items: Array<any>) { return (<Array<any>>this).splice(position, 0, ...items); } },
selectMany: { value: function (callbackfn: (value: any, index: number, array: Array<any>) => Array<any>) { return (<Array<any>>this).select(callbackfn).flat(); } },
groupByMap: { value: function (keySelector: (each: any) => any, selector: (each: any) => any) {
const result = new Map<any, Array<any>>();
for (const each of this) {
const key = keySelector(each);
if (!result.has(key)) {
result.set(key, new Array<any>());
}
result.get(key)!.push(selector(each));
}
return result;
}},
groupBy: {
value: function (keySelector: (each: any) => any, selector: (each: any) => any) {
const result = <any>{};
for (const each of this) {
const key = keySelector(each);
(result[key] = result[key] || new Array<any>()).push( selector(each));
}
return result;
}
},
});
declare global {
interface Array<T> {
where: typeof Array.prototype.filter;
select: typeof Array.prototype.map;
any: typeof Array.prototype.some;
all: typeof Array.prototype.every;
/**
* Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
* @param start The zero-based location in the array from which to start removing elements.
* @param deleteCount The number of elements to remove.
* @param items Elements to insert into the array in place of the deleted elements.
*/
insert(start: number, ...items: Array<T>): Array<T>;
/**
* Removes elements from an array returning the deleted elements.
* @param start The zero-based location in the array from which to start removing elements.
* @param deleteCount The number of elements to remove.
*/
remove(start: number, deleteCount?: number): Array<T>;
selectMany<U>(callbackfn: (value: T, index: number, array: Array<T>) => U): Array<U extends ReadonlyArray<infer InnerArr> ? InnerArr : U>;
groupByMap<TKey,TValue>(keySelector: (each: T) => TKey, selector: (each: T) => TValue): Map<TKey, Array<TValue>>;
groupBy<TValue>(keySelector: (each: T) => string, selector: (each: T) => TValue): { [s: string]: Array<TValue> };
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment