Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Array.prototype.forEach #192

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions src/lib/builtins/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,37 @@ pub fn find_index(this: &Value, args: &[Value], interpreter: &mut Interpreter) -
Ok(Gc::new(ValueData::Number(f64::from(-1))))
}

/// Array.prototype.forEach ( callbackFn [ , thisArg ] )
///
/// This method executes the provided callback function for each element in the array.
/// <https://tc39.es/ecma262/#sec-array.prototype.foreach>
pub fn for_each(this: &Value, args: &[Value], interpreter: &mut Interpreter) -> ResultValue {
if args.is_empty() {
return Err(to_value(
"Missing argument for Array.prototype.forEach".to_string(),
));
}

let callback_arg = args.get(0).expect("Could not get `callbackFn` argument.");

let this_arg = args
.get(1)
.cloned()
.unwrap_or_else(|| Gc::new(ValueData::Undefined));
Copy link
Contributor

@bojan88 bojan88 Oct 27, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you can replace this line with .unwrap_or(&Gc::new(ValueData::Undefined));

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

clippy is going to complain that you are not using unwrap_or_else().

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can use the undefined() function, defined in src/lib/builtins/value.rs


let length: i32 =
from_value(this.get_field_slice("length")).expect("Could not get `length` property.");

for i in 0..length {
let element = this.get_field(&i.to_string());
let arguments = vec![element.clone(), to_value(i), this.clone()];

interpreter.call(callback_arg, &this_arg, arguments)?;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

callback should not be called for undefined values. Also, can you please add tests for cases where array is modified in the callback? For ex. new elements are added to array, elements inserted in the middle, elements deleted.

MDN has a few examples on how this function should work in such cases here.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Im not sure this is quite right, it does run for undefined values, just not values that have been deleted

}

Ok(Gc::new(ValueData::Undefined))
}

pub fn includes_value(this: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue {
let search_element = args
.get(0)
Expand Down Expand Up @@ -526,6 +557,7 @@ pub fn create_constructor(global: &Value) -> Value {
array_prototype.set_field_slice("every", to_value(every as NativeFunctionData));
array_prototype.set_field_slice("find", to_value(find as NativeFunctionData));
array_prototype.set_field_slice("findIndex", to_value(find_index as NativeFunctionData));
array_prototype.set_field_slice("forEach", to_value(for_each as NativeFunctionData));
array_prototype.set_field_slice("includes", includes_func);
array_prototype.set_field_slice("indexOf", index_of_func);
array_prototype.set_field_slice("lastIndexOf", last_index_of_func);
Expand Down Expand Up @@ -929,4 +961,27 @@ mod tests {
let second_in_many = forward(&mut engine, "duplicates.includes('d')");
assert_eq!(second_in_many, String::from("false"));
}

#[test]
fn for_each() {
let realm = Realm::create();
let mut engine = Executor::new(realm);
let init = r#"
var a = [2, 3, 4, 5];
var sum = 0;
var indexSum = 0;
var listLengthSum = 0;
function callingCallback(item, index, list) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could test using this inside the callback.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, come to think of it, I am not sure this has been implemented. However, you could add a TODO for when it is.

sum += item;
indexSum += index;
listLengthSum += list.length;
}
a.forEach(callingCallback);
"#;
forward(&mut engine, init);

assert_eq!(forward(&mut engine, "sum"), "14");
assert_eq!(forward(&mut engine, "indexSum"), "6");
assert_eq!(forward(&mut engine, "listLengthSum"), "16");
}
}