From 0851025ca5352af0efafb1d8d05295d87ac5c74d Mon Sep 17 00:00:00 2001 From: Nick Fitzgerald Date: Mon, 25 Jun 2018 16:19:07 -0700 Subject: [PATCH] js: Implement bindings for Array.prototype.filter --- src/js.rs | 7 +++++++ tests/all/js_globals/Array.rs | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/src/js.rs b/src/js.rs index e90f2872c..cef43b162 100644 --- a/src/js.rs +++ b/src/js.rs @@ -91,6 +91,13 @@ extern { #[wasm_bindgen(method)] pub fn fill(this: &Array, value: JsValue, start: u32, end: u32) -> Array; + /// The `filter()` method creates a new array with all elements that pass the + /// test implemented by the provided function. + /// + /// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter + #[wasm_bindgen(method)] + pub fn filter(this: &Array, predicate: &mut FnMut(JsValue, u32, Array) -> bool) -> Array; + /// The length property of an object which is an instance of type Array /// sets or returns the number of elements in that array. The value is an /// unsigned, 32-bit integer that is always numerically greater than the diff --git a/tests/all/js_globals/Array.rs b/tests/all/js_globals/Array.rs index 24ea11078..e73f03c4c 100755 --- a/tests/all/js_globals/Array.rs +++ b/tests/all/js_globals/Array.rs @@ -2,6 +2,39 @@ use project; +#[test] +fn filter() { + project() + .file("src/lib.rs", r#" + #![feature(proc_macro, wasm_custom_section)] + + extern crate wasm_bindgen; + use wasm_bindgen::prelude::*; + use wasm_bindgen::js; + + #[wasm_bindgen] + pub fn keep_numbers(array: &js::Array) -> js::Array { + array.filter(&mut |x, _, _| x.as_f64().is_some()) + } + + "#) + .file("test.ts", r#" + import * as assert from "assert"; + import * as wasm from "./out"; + + export function test() { + let characters = ["a", "c", "x", "n"]; + let numbers = [1, 2, 3, 4]; + let mixed = ["a", 1, "b", 2]; + + assert.deepStrictEqual(wasm.keep_numbers(characters), []); + assert.deepStrictEqual(wasm.keep_numbers(numbers), numbers); + assert.deepStrictEqual(wasm.keep_numbers(mixed), [1, 2]); + } + "#) + .test() +} + #[test] fn index_of() { project()