Skip to content

Commit

Permalink
Merge pull request #1573 from not-an-aardvark/implement-flat-and-flatmap
Browse files Browse the repository at this point in the history
Add Array#flat and Array#flatMap to js-sys (fixes #1454)
  • Loading branch information
alexcrichton authored Jun 4, 2019
2 parents 6ac61b5 + 5c5c13c commit b11b6df
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
17 changes: 17 additions & 0 deletions crates/js-sys/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<JsValue>,
) -> 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)
Expand Down
38 changes: 38 additions & 0 deletions crates/js-sys/tests/wasm/Array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"];
Expand Down

0 comments on commit b11b6df

Please sign in to comment.