From 4a96ba3c72f163cb54f749caebc70c6bf520a51c Mon Sep 17 00:00:00 2001 From: Matt Long Date: Wed, 20 Jun 2018 17:16:57 -0400 Subject: [PATCH] add binding for indexOf --- src/js.rs | 12 ++++++++++ tests/all/js_globals/Array.rs | 41 +++++++++++++++++++++++++++++++++++ tests/all/js_globals/mod.rs | 1 + 3 files changed, 54 insertions(+) create mode 100644 tests/all/js_globals/Array.rs diff --git a/src/js.rs b/src/js.rs index f77901977..0d39a508b 100644 --- a/src/js.rs +++ b/src/js.rs @@ -94,3 +94,15 @@ extern { } + +// Array +#[wasm_bindgen] +extern { + pub type Array; + + /// The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present. + /// + /// http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf + #[wasm_bindgen(method, js_name = indexOf)] + pub fn index_of(this: &Array, value: JsValue, from_index: i32) -> i32; +} \ No newline at end of file diff --git a/tests/all/js_globals/Array.rs b/tests/all/js_globals/Array.rs new file mode 100644 index 000000000..f46992536 --- /dev/null +++ b/tests/all/js_globals/Array.rs @@ -0,0 +1,41 @@ +#![allow(non_snake_case)] + +use project; + +#[test] +fn index_of() { + project() + .file("src/lib.rs", r#" + #![feature(proc_macro, wasm_custom_section)] + + extern crate wasm_bindgen; + use wasm_bindgen::prelude::*; + use wasm_bindgen::js; + + #[wasm_bindgen] + pub fn get_index_of(this: &js::Array, value: JsValue, from_index: i32) -> i32 { + this.index_of(value, from_index) + } + + "#) + .file("test.ts", r#" + import * as assert from "assert"; + import * as wasm from "./out"; + + export function test() { + let characters = ["a", "c", "x", "n"]; + let index = wasm.get_index_of(characters, "x", 0); + let notFoundIndex = wasm.get_index_of(characters, "z", 0); + + assert.equal(index, 2); + assert.equal(notFoundIndex, -1); + + let withFromIndex = wasm.get_index_of(characters, "x", -3); + let withFromIndexNotFound = wasm.get_index_of(characters, "a", -2); + + assert.equal(withFromIndex, 2); + assert.equal(withFromIndexNotFound, -1); + } + "#) + .test() +} diff --git a/tests/all/js_globals/mod.rs b/tests/all/js_globals/mod.rs index a7eaaeebd..8ab08574d 100644 --- a/tests/all/js_globals/mod.rs +++ b/tests/all/js_globals/mod.rs @@ -3,6 +3,7 @@ use super::project; mod Object; +mod Array; #[test] #[cfg(feature = "std")]