diff --git a/src/js.rs b/src/js.rs index ff2d5eae7..715711ea3 100644 --- a/src/js.rs +++ b/src/js.rs @@ -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. /// diff --git a/tests/all/js_globals/Array.rs b/tests/all/js_globals/Array.rs index e8ce5119a..33b01723a 100644 --- a/tests/all/js_globals/Array.rs +++ b/tests/all/js_globals/Array.rs @@ -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() +}