Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save vishnuroshan/b33b847e98d0ea3ffe5a351ff20b1c39 to your computer and use it in GitHub Desktop.
Save vishnuroshan/b33b847e98d0ea3ffe5a351ff20b1c39 to your computer and use it in GitHub Desktop.
Typescript custom array methods with generics. this is a exercise to understand how generics work and where to use them in real life
interface Array<T> {
customEvery(callback: (each: T, index?: number, array?: Array<T>) => boolean): boolean;
}
Array.prototype.customEvery = function(callback) {
let res= []
for (let i = 0; i < this.length; i++) res.push(callback(this[i], i, this));
return res.includes(false) ? false : true
}
const a = [1, 2, 3, 4, 5].customEvery((each)=>each > 1);
const b = [2, 3, 4, 5, 6].customEvery((each)=>each > 1);
console.log(a) // output: false
console.log(b) // output: true
interface Array<T> {
customFind(matcher: (each: T, index?: number, array?: Array<T>)=> boolean): T | undefined;
}
Array.prototype.customFind = function(matcher) {
for (let i = 0; i < this.length; i++) if(matcher(this[i], i, this)) return this[i]
}
const array: number[] = [1,2,3,4,5,6,7]
console.log(array.customFind((each)=>each===1)) // output: 1
console.log(array.customFind((each)=>each===11)) // output: undefined
interface Array<T> {
customSome(callback: (each: T, index?: number, array?: Array<T>) => boolean): boolean;
}
Array.prototype.customSome = function (callback) {
let res = []
for (let i = 0; i < this.length; i++) res.push(callback(this[i], i, this));
return res.includes(true) ? true : false
}
const a = [1, 1, 1, 1, 1].customSome((each) => each > 1);
const b = [1, 2, 3, 4, 5, 6].customSome((each) => each > 1);
console.log(a) // output: false
console.log(b) // output: true
interface Array<T> {
customReduce<TElement, TResult>(reducer: (prev: TResult, curr: TElement, index?: number, array?: Array<T>) => TResult, initVal: TResult): TResult;
}
Array.prototype.customReduce = function(reducer, initial) {
let result = initial;
for (let elem of this) result = reducer(result, elem);
return result
}
const rr = [1, 2, 3, 4, 5].customReduce<number, {[key: string]: number}>((prev, curr) => {
if (!prev[`-${curr}-`]) prev[`-${curr}-`] = curr
return prev
}, {});
interface MyInterface {
id: number;
name: string;
properties: string[];
}
const myObject: MyInterface = {
id: 1,
name: 'foo',
properties: ['a', 'b', 'c']
};
function getValue(value: keyof MyInterface) {
return myObject[value];
}
getValue('id'); // 1
getValue('count') // Throws compilation error: Argument of type '"count"' is not assignable to parameter of type '"id" | "name" | "properties"'.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment