jsshort
Version:
It will make your codes much short and easiar
71 lines (61 loc) • 2.47 kB
text/typescript
// Define the methods
export function add<T>(this: T[]): T[] {
return this.concat();
}
export function ind<T>(this: T[], item: T): number {
return this.indexOf(item);
}
export function lstInd<T>(this: T[], item: T): number {
return this.lastIndexOf(item);
}
export function inArray<T>(this: T[], item: T): boolean {
return this.includes(item);
}
export function forE<T>(this: T[], callback: (value: T, index: number, array: T[]) => void): void {
for (let i = 0; i < this.length; i++) {
callback(this[i] as any, i, this);
}
}
export function rdc<T>(this: T[], callback: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T {
let accumulator:any = initialValue !== undefined ? initialValue : this[0];
for (let i = initialValue !== undefined ? 0 : 1; i < this.length; i++) {
accumulator = callback(accumulator, this[i] as any, i, this);
}
return accumulator;
}
export function rdcR<T>(this: T[], callback: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T {
let accumulator:any = initialValue !== undefined ? initialValue : this[this.length - 1];
for (let i = this.length - 2; i >= 0; i--) {
accumulator = callback(accumulator as any, this[i] as any, i, this);
}
return accumulator;
}
export function fndInd<T>(this: T[], callback: (value: T, index: number, array: T[]) => boolean): number {
for (let i = 0; i < this.length; i++) {
if (callback(this[i] as any, i, this)) {
return i;
}
}
return -1;
}
// Add these methods to the Array.prototype
declare global {
interface Array<T> {
add(): T[];
ind(item: T): number;
lstInd(item: T): number;
inArray(item: T): boolean;
forE(callback: (value: T, index: number, array: T[]) => void): void;
rdc(callback: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T;
rdcR(callback: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T;
fndInd(callback: (value: T, index: number, array: T[]) => boolean): number;
}
}
Array.prototype.add = add;
Array.prototype.ind = ind;
Array.prototype.lstInd = lstInd;
Array.prototype.inArray = inArray;
Array.prototype.forE = forE;
Array.prototype.rdc = rdc;
Array.prototype.rdcR = rdcR;
Array.prototype.fndInd = fndInd;