Skip to content

Commit

Permalink
Add js_sys::Array::set_length (#3246)
Browse files Browse the repository at this point in the history
Fixes #3244
  • Loading branch information
Liamolucko authored Jan 19, 2023
1 parent e218b7d commit 979b335
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
13 changes: 13 additions & 0 deletions crates/js-sys/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
27 changes: 27 additions & 0 deletions crates/js-sys/tests/wasm/Array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Vec<_>>(),
[1.0, 2.0, 3.0].map(|x| JsValue::from_f64(x))
);

array.set_length(7);
assert_eq!(
array.iter().collect::<Vec<_>>(),
[1.0, 2.0, 3.0]
.iter()
.copied()
.map(|x| JsValue::from_f64(x))
.chain([JsValue::UNDEFINED; 4])
.collect::<Vec<_>>()
);

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();
Expand Down

0 comments on commit 979b335

Please sign in to comment.