Skip to content

Commit d7857da

Browse files
committed
binding for Array.prototype.map()
1 parent 92dd8e8 commit d7857da

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/js.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,16 @@ extern "C" {
216216
#[wasm_bindgen(method, getter, structural)]
217217
pub fn length(this: &Array) -> u32;
218218

219+
/// map calls a provided callback function once for each element in an array,
220+
/// in order, and constructs a new array from the results. callback is invoked
221+
/// only for indexes of the array which have assigned values, including undefined.
222+
/// It is not called for missing elements of the array (that is, indexes that have
223+
/// never been set, which have been deleted or which have never been assigned a value).
224+
///
225+
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
226+
#[wasm_bindgen(method)]
227+
pub fn map(this: &Array, predicate: &mut FnMut(JsValue, u32, Array) -> JsValue) -> Array;
228+
219229
/// The pop() method removes the last element from an array and returns that
220230
/// element. This method changes the length of the array.
221231
///

tests/all/js_globals/Array.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -796,3 +796,37 @@ fn find() {
796796
)
797797
.test()
798798
}
799+
800+
#[test]
801+
fn map() {
802+
project()
803+
.file(
804+
"src/lib.rs",
805+
r#"
806+
#![feature(proc_macro, wasm_custom_section)]
807+
808+
extern crate wasm_bindgen;
809+
use wasm_bindgen::prelude::*;
810+
use wasm_bindgen::js;
811+
use JsValue;
812+
813+
#[wasm_bindgen]
814+
pub fn array_map(array: &js::Array) -> js::Array {
815+
array.map(&mut |el, _, _| JsValue::from_f64(el.as_f64().unwrap().sqrt()))
816+
}
817+
"#,
818+
)
819+
.file(
820+
"test.js",
821+
r#"
822+
import * as assert from "assert";
823+
import * as wasm from "./out";
824+
825+
export function test() {
826+
const numbers = [1, 4, 9];
827+
assert.deepStrictEqual(wasm.array_map(numbers), [1, 2, 3]);
828+
}
829+
"#,
830+
)
831+
.test()
832+
}

0 commit comments

Comments
 (0)