Skip to content

Binding for Array.prototype.map() #453

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 10, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/js.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,16 @@ extern "C" {
#[wasm_bindgen(method, getter, structural)]
pub fn length(this: &Array) -> u32;

/// map calls a provided callback function once for each element in an array,
/// in order, and constructs a new array from the results. callback is invoked
/// only for indexes of the array which have assigned values, including undefined.
/// It is not called for missing elements of the array (that is, indexes that have
/// never been set, which have been deleted or which have never been assigned a value).
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
#[wasm_bindgen(method)]
pub fn map(this: &Array, predicate: &mut FnMut(JsValue, u32, Array) -> JsValue) -> Array;

/// The pop() method removes the last element from an array and returns that
/// element. This method changes the length of the array.
///
Expand Down
34 changes: 34 additions & 0 deletions tests/all/js_globals/Array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -796,3 +796,37 @@ fn find() {
)
.test()
}

#[test]
fn map() {
project()
.file(
"src/lib.rs",
r#"
#![feature(proc_macro, wasm_custom_section)]

extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
use wasm_bindgen::js;
use JsValue;

#[wasm_bindgen]
pub fn array_map(array: &js::Array) -> js::Array {
array.map(&mut |el, _, _| JsValue::from_f64(el.as_f64().unwrap().sqrt()))
}
"#,
)
.file(
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";

export function test() {
const numbers = [1, 4, 9];
assert.deepStrictEqual(wasm.array_map(numbers), [1, 2, 3]);
}
"#,
)
.test()
}