Skip to main content

rustolio_utils/web_sys/
array.rs

1//
2// SPDX-License-Identifier: MPL-2.0
3//
4// Copyright (c) 2026 Tobias Binnewies. All rights reserved.
5//
6// This Source Code Form is subject to the terms of the Mozilla Public
7// License, v. 2.0. If a copy of the MPL was not distributed with this
8// file, You can obtain one at http://mozilla.org/MPL/2.0/.
9//
10
11use js_sys::{Array, JsString};
12use wasm_bindgen::JsCast;
13
14pub trait ArrayExt {
15    fn from_js_iter<Item: JsCast>(iter: impl IntoIterator<Item = Item>) -> Array;
16    fn from_string_iter(iter: impl IntoIterator<Item = String>) -> Array;
17    fn into_js_collection<I, Item>(&self) -> I
18    where
19        I: FromIterator<Item>,
20        Item: JsCast;
21    fn into_string_collection<I>(&self) -> I
22    where
23        I: FromIterator<String>;
24}
25
26impl ArrayExt for Array {
27    fn from_js_iter<Item: JsCast>(iter: impl IntoIterator<Item = Item>) -> Array {
28        let iter = iter.into_iter();
29        let array = Array::new_with_length(iter.size_hint().0 as u32);
30        for (i, item) in iter.enumerate() {
31            array.set(i as u32, item.into());
32        }
33        array
34    }
35
36    fn from_string_iter(iter: impl IntoIterator<Item = String>) -> Array {
37        Array::from_js_iter(iter.into_iter().map(JsString::from))
38    }
39
40    fn into_js_collection<I, Item>(&self) -> I
41    where
42        I: FromIterator<Item>,
43        Item: JsCast,
44    {
45        I::from_iter((0..self.length()).map(|i| self.get(i).unchecked_into::<Item>()))
46    }
47
48    fn into_string_collection<I>(&self) -> I
49    where
50        I: FromIterator<String>,
51    {
52        I::from_iter((0..self.length()).map(|i| self.get(i).unchecked_into::<JsString>().into()))
53    }
54}