Last active
September 10, 2021 16:13
-
-
Save brycetshaw/54ee9c5e28fd53316f37afc68521e6a9 to your computer and use it in GitHub Desktop.
extending the array class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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