mirror of
https://github.com/fluencelabs/assemblyscript
synced 2025-06-15 07:51:32 +00:00
Implement Array#map, Array#forEach, Array#filter, Array#reduceRight (#81)
This commit is contained in:
@ -142,6 +142,35 @@ export class Array<T> {
|
||||
return element;
|
||||
}
|
||||
|
||||
forEach(callbackfn: (value: T, index: i32, array: Array<T>) => void): void {
|
||||
var buffer = this.buffer_;
|
||||
for (let index = 0, toIndex = this.length_; index < toIndex && index < this.length_; ++index) {
|
||||
callbackfn(loadUnsafe<T>(buffer, index), index, this);
|
||||
}
|
||||
}
|
||||
|
||||
map<U>(callbackfn: (value: T, index: i32, array: Array<T>) => U): Array<U> {
|
||||
var buffer = this.buffer_;
|
||||
var length = this.length_;
|
||||
var result = new Array<U>(length);
|
||||
var resultBuffer = result.buffer_;
|
||||
for (let index = 0; index < length && index < this.length_; ++index) {
|
||||
storeUnsafe<U>(resultBuffer, index, callbackfn(loadUnsafe<T>(buffer, index), index, this));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
filter(callbackfn: (value: T, index: i32, array: Array<T>) => bool): Array<T> {
|
||||
var buffer = this.buffer_;
|
||||
var length = this.length_;
|
||||
var result = new Array<T>();
|
||||
for (let index = 0; index < length && index < this.length_; ++index) {
|
||||
let value = loadUnsafe<T>(buffer, index);
|
||||
if (callbackfn(value, index, this)) result.push(value);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
reduce<U>(
|
||||
callbackfn: (previousValue: U, currentValue: T, currentIndex: i32, array: Array<T>) => U,
|
||||
initialValue: U
|
||||
@ -154,6 +183,18 @@ export class Array<T> {
|
||||
return accum;
|
||||
}
|
||||
|
||||
reduceRight<U>(
|
||||
callbackfn: (previousValue: U, currentValue: T, currentIndex: i32, array: Array<T>) => U,
|
||||
initialValue: U
|
||||
): U {
|
||||
var accum = initialValue;
|
||||
var buffer = this.buffer_;
|
||||
for (let index: i32 = this.length_ - 1; index >= 0; --index) {
|
||||
accum = callbackfn(accum, loadUnsafe<T>(buffer, index), index, this);
|
||||
}
|
||||
return accum;
|
||||
}
|
||||
|
||||
shift(): T {
|
||||
var length = this.length_;
|
||||
if (length < 1) throw new RangeError("Array is empty");
|
||||
@ -245,7 +286,7 @@ export class Array<T> {
|
||||
return this;
|
||||
}
|
||||
|
||||
sort(comparator: (a: T, b: T) => i32 = defaultComparator<T>()): Array<T> {
|
||||
sort(comparator: (a: T, b: T) => i32 = defaultComparator<T>()): this {
|
||||
var length = this.length_;
|
||||
if (length <= 1) return this;
|
||||
var buffer = this.buffer_;
|
||||
|
Reference in New Issue
Block a user