Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add TypedArray#filter #818

Merged
merged 7 commits into from
Sep 6, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 11 additions & 13 deletions std/assembly/typedarray.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1415,28 +1415,26 @@ function FILTER<TArray extends ArrayBufferView, T>(
fn: (value: T, index: i32, self: TArray) => bool,
): TArray {
var len = array.length;
var out = instantiate<TArray>(len);
var dataStart = array.dataStart;
var outDataStart = out.dataStart;
var j = 0;
var byteLength = len << alignof<T>();
MaxGraey marked this conversation as resolved.
Show resolved Hide resolved
var out = changetype<TArray>(__alloc(offsetof<TArray>(), idof<TArray>()));
var buffer = __alloc(byteLength, idof<ArrayBuffer>());
var dataStart = array.dataStart;
var j: usize = 0;
for (let i = 0; i < len; i++) {
let value = load<T>(dataStart + (<usize>i << alignof<T>()));
if (fn(value, i, array)) {
store<T>(
outDataStart + (<usize>j << alignof<T>()),
buffer + (j++ << alignof<T>()),
value
);
++j;
}
}
// shrink output buffer
var finalLenght = <usize>j << alignof<T>();
var newStartData = __realloc(outDataStart, finalLenght);
if (newStartData !== outDataStart) {
out.data = changetype<ArrayBuffer>(newStartData); // retain
out.dataStart = newStartData;
}
out.dataLength = finalLenght;
var length = j << alignof<T>();
var data = __realloc(buffer, length);
out.data = changetype<ArrayBuffer>(data); // retain
out.dataStart = data;
out.dataLength = length;
return out;
}

Expand Down
Loading