mirror of
https://github.com/rustwasm/wasm-bindgen.git
synced 2024-12-15 12:44:31 +03:00
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:
commit
b11b6dfe5d
@ -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)
|
||||
|
@ -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"];
|
||||
|
Loading…
Reference in New Issue
Block a user