Merge pull request #1573 from not-an-aardvark/implement-flat-and-flatmap

Add Array#flat and Array#flatMap to js-sys (fixes #1454)
This commit is contained in:
Alex Crichton 2019-06-04 09:59:40 -05:00 committed by GitHub
commit b11b6dfe5d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 55 additions and 0 deletions

View File

@ -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)

View File

@ -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"];