Use the faster childIndexOf() approach in JS too

I was wondering if the different approach to childIndexOf()
implemented in PHP in b8d7a75c34 would
be faster in JS as well, and yes, it is.

Our test suite now takes (on my machine):
* Chrome: 8337 ms → 7355 ms (average over 5 tries)
* Firefox: 5321 ms → 5044 ms (average over 5 tries)

Change-Id: I71963eeb92dcea9bfd59cbf01a7aa0b7de5d9cf1
This commit is contained in:
Bartosz Dziewoński 2020-05-22 19:09:21 +02:00
parent 16cf49e7e4
commit 8f583a23be
3 changed files with 21 additions and 15 deletions

View file

@ -754,13 +754,13 @@ function getComments( rootNode ) {
match = timestamps[ nextTimestamp ][ 1 ];
range = {
startContainer: startNode.parentNode,
startOffset: Array.prototype.indexOf.call( startNode.parentNode.childNodes, startNode ),
startOffset: utils.childIndexOf( startNode ),
endContainer: node,
endOffset: match.index + match[ 0 ].length
};
sigRange = {
startContainer: firstSigNode.parentNode,
startOffset: Array.prototype.indexOf.call( firstSigNode.parentNode.childNodes, firstSigNode ),
startOffset: utils.childIndexOf( firstSigNode ),
endContainer: node,
endOffset: match.index + match[ 0 ].length
};

View file

@ -15,6 +15,20 @@ function getNativeRange( comment ) {
return nativeRange;
}
/**
* Get the index of a node in its parentNode's childNode list
*
* @param {Node} child
* @return {number} Index in parentNode's childNode list
*/
function childIndexOf( child ) {
var i = 0;
while ( ( child = child.previousSibling ) ) {
i++;
}
return i;
}
/**
* Find closest ancestor element using one of the given tag names.
*
@ -48,6 +62,7 @@ function htmlTrim( str ) {
module.exports = {
getNativeRange: getNativeRange,
childIndexOf: childIndexOf,
closestElement: closestElement,
htmlTrim: htmlTrim
};

View file

@ -1,3 +1,6 @@
var
utils = require( 'ext.discussionTools.init' ).utils;
module.exports = {};
/* eslint-disable qunit/no-commented-tests */
@ -46,18 +49,6 @@ module.exports.overrideMwConfig = function ( config ) {
);
};
/**
* Get the index of a node in its parentNode's childNode list
*
* @copyright 2011-2019 VisualEditor Team and others; see http://ve.mit-license.org
*
* @param {Node} node The node
* @return {number} Index in parentNode's childNode list
*/
function parentIndex( node ) {
return Array.prototype.indexOf.call( node.parentNode.childNodes, node );
}
/**
* Get the offset path from ancestor to offset in descendant
*
@ -76,7 +67,7 @@ function getOffsetPath( ancestor, node, nodeOffset ) {
console.log( node, 'is not a descendant of', ancestor );
throw new Error( 'Not a descendant' );
}
path.unshift( parentIndex( node ) );
path.unshift( utils.childIndexOf( node ) );
node = node.parentNode;
}
return path;