| 1 |
# Iterating over JavaScript Values |
| 2 |
|
| 3 |
## Methods That Return `js_sys::Iterator` |
| 4 |
|
| 5 |
Some JavaScript collections have methods for iterating over their values or |
| 6 |
keys: |
| 7 |
|
| 8 |
* [`Map::values`](https://rustwasm.github.io/wasm-bindgen/api/js_sys/struct.Map.html#method.values) |
| 9 |
* [`Set::keys`](https://rustwasm.github.io/wasm-bindgen/api/js_sys/struct.Set.html#method.keys) |
| 10 |
* etc... |
| 11 |
|
| 12 |
These methods return |
| 13 |
[`js_sys::Iterator`](https://rustwasm.github.io/wasm-bindgen/api/js_sys/struct.Iterator.html), |
| 14 |
which is the Rust representation of a JavaScript object that has a `next` method |
| 15 |
that either returns the next item in the iteration, notes that iteration has |
| 16 |
completed, or throws an error. That is, `js_sys::Iterator` represents an object |
| 17 |
that implements [the duck-typed JavaScript iteration |
| 18 |
protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols). |
| 19 |
|
| 20 |
`js_sys::Iterator` can be converted into a Rust iterator either by reference |
| 21 |
(into |
| 22 |
[`js_sys::Iter<'a>`](https://rustwasm.github.io/wasm-bindgen/api/js_sys/struct.Iter.html)) |
| 23 |
or by value (into |
| 24 |
[`js_sys::IntoIter`](https://rustwasm.github.io/wasm-bindgen/api/js_sys/struct.IntoIter.html)). The |
| 25 |
Rust iterator will yield items of type `Result<JsValue>`. If it yields an |
| 26 |
`Ok(...)`, then the JS iterator protocol returned an element. If it yields an |
| 27 |
`Err(...)`, then the JS iterator protocol threw an exception. |
| 28 |
|
| 29 |
```rust |
| 30 |
use wasm_bindgen::prelude::*; |
| 31 |
|
| 32 |
#[wasm_bindgen] |
| 33 |
pub fn count_strings_in_set(set: &js_sys::Set) -> u32 { |
| 34 |
let mut count = 0; |
| 35 |
|
| 36 |
// Call `keys` to get an iterator over the set's elements. Because this is |
| 37 |
// in a `for ... in ...` loop, Rust will automatically call its |
| 38 |
// `IntoIterator` trait implementation to convert it into a Rust iterator. |
| 39 |
for x in set.keys() { |
| 40 |
// We know the built-in iterator for set elements won't throw |
| 41 |
// exceptions, so just unwrap the element. If this was an untrusted |
| 42 |
// iterator, we might want to explicitly handle the case where it throws |
| 43 |
// an exception instead of returning a `{ value, done }` object. |
| 44 |
let x = x.unwrap(); |
| 45 |
|
| 46 |
// If `x` is a string, increment our count of strings in the set! |
| 47 |
if x.is_string() { |
| 48 |
count += 1; |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
count |
| 53 |
} |
| 54 |
``` |
| 55 |
|
| 56 |
## Iterating Over <u>Any</u> JavaScript Object that Implements the Iterator Protocol |
| 57 |
|
| 58 |
You could manually test for whether an object implements JS's duck-typed |
| 59 |
iterator protocol, and if so, convert it into a `js_sys::Iterator` that you can |
| 60 |
finally iterate over. You don't need to do this by-hand, however, since we |
| 61 |
bundled this up as [the `js_sys::try_iter` |
| 62 |
function!](https://rustwasm.github.io/wasm-bindgen/api/js_sys/fn.try_iter.html) |
| 63 |
|
| 64 |
For example, we can write a function that collects the numbers from any JS |
| 65 |
iterable and returns them as an `Array`: |
| 66 |
|
| 67 |
```rust |
| 68 |
use wasm_bindgen::prelude::*; |
| 69 |
|
| 70 |
#[wasm_bindgen] |
| 71 |
pub fn collect_numbers(some_iterable: &JsValue) -> Result<js_sys::Array, JsValue> { |
| 72 |
let nums = js_sys::Array::new(); |
| 73 |
|
| 74 |
let iterator = js_sys::try_iter(some_iterable)?.ok_or_else(|| { |
| 75 |
"need to pass iterable JS values!" |
| 76 |
})?; |
| 77 |
|
| 78 |
for x in iterator { |
| 79 |
// If the iterator's `next` method throws an error, propagate it |
| 80 |
// up to the caller. |
| 81 |
let x = x?; |
| 82 |
|
| 83 |
// If `x` is a number, add it to our array of numbers! |
| 84 |
if x.as_f64().is_some() { |
| 85 |
nums.push(&x); |
| 86 |
} |
| 87 |
} |
| 88 |
|
| 89 |
Ok(nums) |
| 90 |
} |
| 91 |
``` |