Merge pull request #397 from ZerothLaw/Issue275/ArrayFind

Issue #275: Added Array.prototype.find binding
This commit is contained in:
Sendil Kumar N 2018-07-06 09:22:46 +02:00 committed by GitHub
commit a65b6c7003
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 45 additions and 0 deletions

View File

@ -141,6 +141,13 @@ extern "C" {
#[wasm_bindgen(method)]
pub fn filter(this: &Array, predicate: &mut FnMut(JsValue, u32, Array) -> bool) -> Array;
/// The `find()` method returns the value of the first element in the array that satisfies
/// the provided testing function. Otherwise `undefined` is returned.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
#[wasm_bindgen(method)]
pub fn find(this: &Array, predicate: &mut FnMut(JsValue, u32, Array) -> bool) -> JsValue;
/// The includes() method determines whether an array includes a certain
/// element, returning true or false as appropriate.
///

View File

@ -758,3 +758,41 @@ fn every() {
)
.test()
}
#[test]
fn find() {
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 array_find_first_even_number(array: &js::Array) -> JsValue {
array.find(&mut |el, _, _| el.as_f64().unwrap() % 2f64 == 0f64)
}
"#,
)
.file(
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
const arrayEven = [2, 4, 6, 8];
const arrayOdd = [1, 3, 5, 7];
const arrayMixed = [3, 5, 7, 10];
assert.equal(wasm.array_find_first_even_number(arrayEven), 2);
assert.equal(wasm.array_find_first_even_number(arrayOdd), undefined);
assert.equal(wasm.array_find_first_even_number(arrayMixed), 10);
}
"#,
)
.test()
}