Skip to content

Commit a9ca64b

Browse files
author
robertdurst
committed
Implement Array.length binding
1 parent 9e01e67 commit a9ca64b

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/js.rs

+7
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,13 @@ extern {
112112
extern {
113113
pub type Array;
114114

115+
/// The length property of an object which is an instance of type Array sets or returns the number of elements in that array.
116+
/// The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
117+
///
118+
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length
119+
#[wasm_bindgen(method, getter, structural)]
120+
pub fn length(this: &Array) -> u32;
121+
115122
/// 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.
116123
///
117124
/// http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

tests/all/js_globals/Array.rs

+34
Original file line numberDiff line numberDiff line change
@@ -422,3 +422,37 @@ fn includes() {
422422
"#)
423423
.test()
424424
}
425+
426+
427+
#[test]
428+
fn length() {
429+
project()
430+
.file("src/lib.rs", r#"
431+
#![feature(proc_macro, wasm_custom_section)]
432+
433+
extern crate wasm_bindgen;
434+
use wasm_bindgen::prelude::*;
435+
use wasm_bindgen::js;
436+
437+
#[wasm_bindgen]
438+
pub fn array_length(this: &js::Array) -> u32 {
439+
this.length()
440+
}
441+
442+
"#)
443+
.file("test.ts", r#"
444+
import * as assert from "assert";
445+
import * as wasm from "./out";
446+
447+
export function test() {
448+
let characters = [8, 5, 4, 3, 1, 2]
449+
let charactersLength = wasm.array_length(characters);
450+
assert.equal(charactersLength, 6);
451+
452+
var empty : number[] = [];
453+
let emptyLength = wasm.array_length(empty);
454+
assert.equal(emptyLength, 0);
455+
}
456+
"#)
457+
.test()
458+
}

0 commit comments

Comments
 (0)