Skip to content

Commit

Permalink
implemented forEach
Browse files Browse the repository at this point in the history
  • Loading branch information
Angelo Ceccato authored and AngeloChecked committed Nov 28, 2023
1 parent 752caff commit 66b6a6d
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
15 changes: 15 additions & 0 deletions boa_engine/src/object/builtins/jstypedarray.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,21 @@ impl JsTypedArray {
}
}

/// Calls `TypedArray.prototype.forEach()`.
#[inline]
pub fn foreach(
&self,
callback: JsFunction,
this_arg: Option<JsValue>,
context: &mut Context,
) -> JsResult<JsValue> {
BuiltinTypedArray::foreach(
&self.inner.clone().into(),
&[callback.into(), this_arg.into_or_undefined()],
context,
)
}

/// Calls `TypedArray.prototype.indexOf()`.
pub fn index_of<T>(
&self,
Expand Down
29 changes: 29 additions & 0 deletions boa_examples/src/bin/jstypedarray.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use boa_engine::{
property::Attribute,
Context, JsResult, JsValue,
};
use boa_gc::{Gc, GcRefCell};

fn main() -> JsResult<()> {
// We create a new `Context` to create a new Javascript executor.
Expand Down Expand Up @@ -87,6 +88,34 @@ fn main() -> JsResult<()> {
Ok(Some(3))
);

// forEach
let array = JsUint8Array::from_iter(vec![1, 2, 3, 4, 5], context)?;
let num_to_modify = Gc::new(GcRefCell::new(0u8));

let js_function = FunctionObjectBuilder::new(
context.realm(),
NativeFunction::from_copy_closure_with_captures(
|_, args, captures, inner_context| {
let element = args
.get(0)
.cloned()
.unwrap_or_default()
.to_uint8(inner_context)
.expect("error at number conversion");

*captures.borrow_mut() += element;
Ok(JsValue::Undefined)
},
Gc::clone(&num_to_modify),
),
)
.build();

let _unused = array.foreach(js_function, None, context);

let borrow = *num_to_modify.borrow();
assert_eq!(borrow, 15u8);

context
.register_global_property(
js_string!("myUint8Array"),
Expand Down

0 comments on commit 66b6a6d

Please sign in to comment.