Problem/Motivation
When reading through the views code I came accross the
core/modules/views/js/base.js
which contains optimizable for loops:
for(var i in pairs) {
if (typeof(pairs[i]) === 'string') {
..
}
}
Which could be done faster with less code
for(var i = 0; i<pairs.length; i++) { .. }
Or even faster but maybe a little bit harder to read
for(var i = pairs.length; i>=0; i--) { .. }
However the real problem is that this loop might cause unintended behaviour if the global Array.prototype is modified:
Array.prototype.hello = "world";
pairs = [];
for(var i in pairs) {
if (typeof(pairs[i]) === 'string') {
console.log(i);
}
}
So the typeof check is not needed as String.prototype.split always returns an array of strings:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global...
Some of the above points also apply for the second loop:
for (var i in chars) {
if (href.indexOf(chars[i]) > -1) {
..
}
}
Proposed resolution
Use for(var i = 0; i<pairs.length; i++) { .. } and remove if (typeof(pairs[i]) === 'string') { so
* it's faster
* requires less code
* is safer
| Comment | File | Size | Author |
|---|---|---|---|
| #11 | views.base_.for-loop-2099599.patch | 1.39 KB | jantimon |
| views.base_.for-loop.patch | 1.2 KB | jantimon |
Comments
Comment #1
nod_looks ok, needs some testing.
When you fill a JS patch, please tag it JS so we can see it :)
Comment #2
jantimon commentedThanks for your advice and your fast response :)
Comment #3
jantimon commentedAny updates on this issue?
Comment #4
jantimon commentedviews.base_.for-loop.patch queued for re-testing.
Comment #5
jantimon commentedhttp://drupalcode.org/project/drupal.git/blob/refs/heads/8.x:/core/modul...
Comment #6
dawehnerPlease tag changes in views with VDC
Comment #7
dawehnerI cannot really review the patch, though I think nod_ can.
Comment #8
damien tournoud commentedIf we are nitpicking, those two uses of
varare strongly discouraged:... because they seem to imply that Javascript is block scoped. It is not: it is *function* scoped, so it is best to have all the local variables declared at the top of the function.
Comment #9
jantimon commentedComment #10
nod_Um unfortunately you're not supposed to RTBC your own issues.
I'm fine with the
var i = 0in the for loop but not on thevar pair, can you move the declaration outside the loop please?Other than that it's fine.
Comment #11
jantimon commentedAlright - I moved the declaration of pair:
Comment #12
nod_Perfect, that works. thanks a lot!
Comment #13
droplet commentedPlease consider this full rewritten patch #2175513: Handle params array in Drupal.Views.parseQueryString JS function. Of course we can keep the for-loop but while + regex would be more readability & less code.
Comment #14
webchickLooks like that issue is still needs work, so let's get this one in in the meantime.
Committed and pushed to 8.x. Thanks!