Page MenuHomePhabricator

Cleanup: Excessive use of forEach loops where there's no need to loop over the whole sets
Closed, ResolvedPublic

Description

Observed in the front-end, it's usual practice to use forEach loops in places where there's no need to iterate over the whole array or set, but only till finding the first element that matches a condition. We can probably do a much better job at having a more performant front-end logic.

E.g. https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/extensions/WikiLambda/+/refs/heads/master/resources/ext.wikilambda.edit/components/types/ZLabelsBlock.vue#263

Event Timeline

I see these possibilities :

  • Either we can use Array.prototype.find because it is supported by all modern browsers and we do not support IE11
  • Otherwise:
    • we can probably use Array.prototype.some just like we currently use Array.prototype.forEach and return true when we want to stop iterating and return`false` otherwise
    • a good old for (...;...;...) loop with a break statement
    • Use some Array.prototype.find polyfill (core-js or even babel which uses it)

(and there might be other possibilities :) )

Resources:

Change 865052 had a related patch set uploaded (by Teleosteen; author: Teleosteen):

[mediawiki/extensions/WikiLambda@master] Fix wrong usage of forEach where looping over the whole set has no sense

https://gerrit.wikimedia.org/r/865052

Change 865052 merged by jenkins-bot:

[mediawiki/extensions/WikiLambda@master] Fix wrong usage of forEach where looping over the whole set has no sense

https://gerrit.wikimedia.org/r/865052