From 5c5c13cf9e6dbb77ad42203358318fb89f1cbebf Mon Sep 17 00:00:00 2001 From: Teddy Katz Date: Mon, 3 Jun 2019 18:32:58 -0400 Subject: [PATCH] Add Array#flat and Array#flatMap to js-sys (fixes #1454) --- crates/js-sys/src/lib.rs | 17 ++++++++++++++ crates/js-sys/tests/wasm/Array.rs | 38 +++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/crates/js-sys/src/lib.rs b/crates/js-sys/src/lib.rs index bdf73ad9f90..d96e784c1b8 100644 --- a/crates/js-sys/src/lib.rs +++ b/crates/js-sys/src/lib.rs @@ -188,6 +188,23 @@ extern "C" { #[wasm_bindgen(method, js_name = findIndex)] pub fn find_index(this: &Array, predicate: &mut dyn FnMut(JsValue, u32, Array) -> bool) -> i32; + /// The flat() method creates a new array with all sub-array elements concatenated into it + /// recursively up to the specified depth. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) + #[wasm_bindgen(method)] + pub fn flat(this: &Array, depth: i32) -> Array; + + /// The flatMap() method first maps each element using a mapping function, then flattens + /// the result into a new array. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap) + #[wasm_bindgen(method, js_name = flatMap)] + pub fn flat_map( + this: &Array, + callback: &mut dyn FnMut(JsValue, u32, Array) -> Vec, + ) -> Array; + /// The `forEach()` method executes a provided function once for each array element. /// /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) diff --git a/crates/js-sys/tests/wasm/Array.rs b/crates/js-sys/tests/wasm/Array.rs index 82969480519..61bd08ed1c4 100644 --- a/crates/js-sys/tests/wasm/Array.rs +++ b/crates/js-sys/tests/wasm/Array.rs @@ -43,6 +43,44 @@ fn filter() { ); } +#[wasm_bindgen_test] +fn flat() { + let array = js_array![ + js_array!["a", "b", "c"], + "d", + js_array!["e", js_array!["f", "g"]] + ]; + + assert_eq!( + to_rust(&array.flat(1).slice(0, 5)), + vec!["a", "b", "c", "d", "e"] + ); + + assert_eq!(array.flat(1).length(), 6); + + assert_eq!( + to_rust(&array.flat(2)), + vec!["a", "b", "c", "d", "e", "f", "g"] + ); +} + +#[wasm_bindgen_test] +fn flat_map() { + let array = js_array![1, 2, 3, 1]; + + assert_eq!( + to_rust( + &array.flat_map(&mut |val, _, _| match val.as_f64().map(|v| v as i32) { + Some(1) => vec![JsString::from("x").into(), JsString::from("x").into()], + Some(2) => vec![], + Some(3) => vec![JsString::from("z").into()], + _ => panic!("Unexpected conversion"), + }) + ), + vec!["x", "x", "z", "x", "x"] + ); +} + #[wasm_bindgen_test] fn index_of() { let chars = js_array!["a", "c", "x", "n"];