Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

forEach should support break #263

@IgorMinar

Description

@IgorMinar

while continue support is already supported by accident, there is no way to do a break.

continue can be done by a simple return already:
//prints all elements but 2
forEach([1,2,3,4], function(i) {
if (i==2) return;
console.log(i);
}

break on the other hand isn't possible to achieve this way, we need to modify forEach to do that. There are three options;

  • throw a special exception which would be caught and matched by forEach
  • return a special value
  • making forEach stateful

I'm not a big fan of using exceptions to control execution flow in non-exceptional cases, so I'm for the second approach. Here is my proposal:
//prints all elements until 2 is reached == only "1"
forEach([1,2,3,4], function(i) {
//break() is a function that returns an immutable object,
//e.g. an empty string
if (i==2) return forEach.break();
console.log(i);
}

I also considered the third approach, but since you'll have to use return if you want to break from the middle of an iterator anyway, we might prevent issues with accidentally forgetting to return.

This third approach would from the user perspective look exactly the same as the code for the second approach above. From angular implementation point of view, things would be more complicated.

When this feature is implemented, we should look at our existing forEach instances and add break where needed.

We should also properly document both continue and break scenarios.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions