Bindings for Array.prototype.reduce(Right)

This commit is contained in:
Tomohide Takao 2018-07-12 22:56:08 +09:00
parent 913b487638
commit a7deb69e80
2 changed files with 80 additions and 0 deletions

View File

@ -240,6 +240,20 @@ extern "C" {
#[wasm_bindgen(method)]
pub fn push(this: &Array, value: JsValue) -> u32;
/// The reduce() method applies a function against an accumulator and each element in
/// the array (from left to right) to reduce it to a single value.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
#[wasm_bindgen(method)]
pub fn reduce(this: &Array, predicate: &mut FnMut(JsValue, JsValue, u32, Array) -> JsValue, initial_value: JsValue) -> JsValue;
/// The reduceRight() method applies a function against an accumulator and each value
/// of the array (from right-to-left) to reduce it to a single value.
///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight
#[wasm_bindgen(method, js_name = reduceRight)]
pub fn reduce_right(this: &Array, predicate: &mut FnMut(JsValue, JsValue, u32, Array) -> JsValue, initial_value: JsValue) -> JsValue;
/// The reverse() method reverses an array in place. The first array
/// element becomes the last, and the last array element becomes the first.
///

View File

@ -830,3 +830,69 @@ fn map() {
)
.test()
}
#[test]
fn reduce() {
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_reduce(array: &js::Array) -> JsValue {
array.reduce(&mut |ac, cr, _, _| JsValue::from_str(&format!("{}{}", &ac.as_string().unwrap(), &cr.as_string().unwrap().as_str())), JsValue::from_str(""))
}
"#,
)
.file(
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
assert.equal(wasm.array_reduce(['0', '1', '2', '3', '4']), '01234');
}
"#,
)
.test()
}
#[test]
fn reduce_right() {
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_reduce_right(array: &js::Array) -> JsValue {
array.reduce_right(&mut |ac, cr, _, _| JsValue::from_str(&format!("{}{}", &ac.as_string().unwrap(), &cr.as_string().unwrap().as_str())), JsValue::from_str(""))
}
"#,
)
.file(
"test.js",
r#"
import * as assert from "assert";
import * as wasm from "./out";
export function test() {
assert.equal(wasm.array_reduce_right(['0', '1', '2', '3', '4']), '43210');
}
"#,
)
.test()
}