From 979b335e4ef1fdd59bfb520d3868a39e61cd703d Mon Sep 17 00:00:00 2001 From: Liam Murphy Date: Fri, 20 Jan 2023 02:11:12 +1100 Subject: [PATCH] Add `js_sys::Array::set_length` (#3246) Fixes #3244 --- crates/js-sys/src/lib.rs | 13 +++++++++++++ crates/js-sys/tests/wasm/Array.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/crates/js-sys/src/lib.rs b/crates/js-sys/src/lib.rs index 838611362b9..92890a62b72 100644 --- a/crates/js-sys/src/lib.rs +++ b/crates/js-sys/src/lib.rs @@ -447,6 +447,19 @@ extern "C" { #[wasm_bindgen(method, getter, structural)] pub fn length(this: &Array) -> u32; + /// Sets the length of the array. + /// + /// If it is set to less than the current length of the array, it will + /// shrink the array. + /// + /// If it is set to more than the current length of the array, it will + /// increase the length of the array, filling the new space with empty + /// slots. + /// + /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length) + #[wasm_bindgen(method, setter)] + pub fn set_length(this: &Array, value: 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. diff --git a/crates/js-sys/tests/wasm/Array.rs b/crates/js-sys/tests/wasm/Array.rs index 02243a86856..3934389f077 100644 --- a/crates/js-sys/tests/wasm/Array.rs +++ b/crates/js-sys/tests/wasm/Array.rs @@ -534,6 +534,33 @@ fn for_each() { assert_eq!(sum_indices_of_evens(&js_array![3, 5, 7, 10]), 3); } +#[wasm_bindgen_test] +fn set_length() { + let array = js_array![1, 2, 3, 4, 5]; + array.set_length(3); + assert_eq!( + array.iter().collect::>(), + [1.0, 2.0, 3.0].map(|x| JsValue::from_f64(x)) + ); + + array.set_length(7); + assert_eq!( + array.iter().collect::>(), + [1.0, 2.0, 3.0] + .iter() + .copied() + .map(|x| JsValue::from_f64(x)) + .chain([JsValue::UNDEFINED; 4]) + .collect::>() + ); + + let mut calls = 0; + array.for_each(&mut |_, _, _| calls += 1); + // The later elements don't get filled with `undefined`, they get filled with + // empty slots, which get skipped by `for_each`. + assert_eq!(calls, 3); +} + #[wasm_bindgen_test] fn array_inheritance() { let array = Array::new();