Skip to content

Instantly share code, notes, and snippets.

@brycetshaw
Last active September 10, 2021 16:13
Show Gist options
  • Save brycetshaw/54ee9c5e28fd53316f37afc68521e6a9 to your computer and use it in GitHub Desktop.
Save brycetshaw/54ee9c5e28fd53316f37afc68521e6a9 to your computer and use it in GitHub Desktop.
extending the array class
export class SuperArray<Data> extends Array {
static from<Data>(input: Data[]): SuperArray<Data> {
return new SuperArray(input);
}
constructor(input: any[]) {
super(input.length);
input.forEach((element, index) => {
this[index] = element;
})
}
toArray(): Data[] {
return [...this];
}
map(...args): SuperArray<Data> {
return new SuperArray(super.map(args));
}
filter(...args): SuperArray<Data> {
return new SuperArray(super.filter(args));
}
split(comparator: (previous: Data, current: Data) => boolean): Data[][] {
return this.reduce((acc, next, index) => {
if(acc.length === 0) {
acc.push([next])
return acc
}
const previous = acc[acc.length - 1]
if(comparator(previous, next)){
acc.push([next])
}
else {
previous.push(next)
}
return acc
},[])
}
at(index): Data {
if (index < 0) {
const reverseIndex = this.length - index;
return reverseIndex >= 0 ? this[reverseIndex] : undefined;
}
return this.length > index ? this[index] : undefined;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment