Skip to content

Commit b11b6df

Browse files
authored
Merge pull request #1573 from not-an-aardvark/implement-flat-and-flatmap
Add Array#flat and Array#flatMap to js-sys (fixes #1454)
2 parents 6ac61b5 + 5c5c13c commit b11b6df

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

crates/js-sys/src/lib.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,23 @@ extern "C" {
188188
#[wasm_bindgen(method, js_name = findIndex)]
189189
pub fn find_index(this: &Array, predicate: &mut dyn FnMut(JsValue, u32, Array) -> bool) -> i32;
190190

191+
/// The flat() method creates a new array with all sub-array elements concatenated into it
192+
/// recursively up to the specified depth.
193+
///
194+
/// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat)
195+
#[wasm_bindgen(method)]
196+
pub fn flat(this: &Array, depth: i32) -> Array;
197+
198+
/// The flatMap() method first maps each element using a mapping function, then flattens
199+
/// the result into a new array.
200+
///
201+
/// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap)
202+
#[wasm_bindgen(method, js_name = flatMap)]
203+
pub fn flat_map(
204+
this: &Array,
205+
callback: &mut dyn FnMut(JsValue, u32, Array) -> Vec<JsValue>,
206+
) -> Array;
207+
191208
/// The `forEach()` method executes a provided function once for each array element.
192209
///
193210
/// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)

crates/js-sys/tests/wasm/Array.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,44 @@ fn filter() {
4343
);
4444
}
4545

46+
#[wasm_bindgen_test]
47+
fn flat() {
48+
let array = js_array![
49+
js_array!["a", "b", "c"],
50+
"d",
51+
js_array!["e", js_array!["f", "g"]]
52+
];
53+
54+
assert_eq!(
55+
to_rust(&array.flat(1).slice(0, 5)),
56+
vec!["a", "b", "c", "d", "e"]
57+
);
58+
59+
assert_eq!(array.flat(1).length(), 6);
60+
61+
assert_eq!(
62+
to_rust(&array.flat(2)),
63+
vec!["a", "b", "c", "d", "e", "f", "g"]
64+
);
65+
}
66+
67+
#[wasm_bindgen_test]
68+
fn flat_map() {
69+
let array = js_array![1, 2, 3, 1];
70+
71+
assert_eq!(
72+
to_rust(
73+
&array.flat_map(&mut |val, _, _| match val.as_f64().map(|v| v as i32) {
74+
Some(1) => vec![JsString::from("x").into(), JsString::from("x").into()],
75+
Some(2) => vec![],
76+
Some(3) => vec![JsString::from("z").into()],
77+
_ => panic!("Unexpected conversion"),
78+
})
79+
),
80+
vec!["x", "x", "z", "x", "x"]
81+
);
82+
}
83+
4684
#[wasm_bindgen_test]
4785
fn index_of() {
4886
let chars = js_array!["a", "c", "x", "n"];

0 commit comments

Comments
 (0)