DEV Community

Discussion on: 5 things I learnt during my latest Javascript Code Kata

Collapse
 
erikpischel profile image
Erik Pischel

Why do you think it will loop twice?

Context: input in this case is a weighted graph like this [["AB", 4], ["BC", 8], ["AC", 5]]. A, B, C are nodes, numbers are weights.

It is just a way to initialize a data structure. filter is used just to avoid "saving" edges like ["AA", 8] in object "set".

Collapse
 
vshyrokov profile image
Viktor Shyrokov

It could loop twice, let's say we have 1 billion of records.

All that records, as example has prop like, isFilterable = true

let's say we have a filter

edges.filter(e => e.isFilterable).forEach(e => { // some logic });

in this case we will loop through all the data twice.

It would be easier to use such a condition in the foreEach directly.

In this case you'll avoid duplicate actions on data.

Yes, filter pretty cool thing, but not in this case where we have filter().foreach()

Thread Thread
 
erikpischel profile image
Erik Pischel

Now I see your point. The advantage I see in this case is that a seperate "filter" step represents a seperate step in the algorithm. Like "step 1: filter out all edges that connect only one node. step 2: ...". If you use the filter condition in the forEach directly it gets more entangled with the next step.

Thanks for your comment.