r99743 MediaWiki - Code Review archive

Repository:MediaWiki
Revision:r99742‎ | r99743 | r99744 >
Date:23:13, 13 October 2011
Author:tparscal
Status:deferred
Tags:
Comment:
Rewrote es.DocumentModel.getOffsetFromNode to use iteration instead of function recursion
Modified paths:
  • /trunk/parsers/wikidom/lib/hype/models/es.DocumentModel.js (modified) (history)

Diff [purge]

Index: trunk/parsers/wikidom/lib/hype/models/es.DocumentModel.js
@@ -446,27 +446,41 @@
447447 * This method is pretty expensive. If you need to get different slices of the same content, get
448448 * the content first, then slice it up locally.
449449 *
450 - * TODO: Rewrite this method to not use recursion, because the function call overhead is expensive
451 - *
452450 * @method
453451 * @param {es.DocumentModelNode} node Node to get offset of
454452 * @returns {Integer} Offset of node or -1 of node was not found
455453 */
456454 es.DocumentModel.prototype.getOffsetFromNode = function( node ) {
457 - var offset = 0;
458 - for ( var i = 0; i < this.length; i++ ) {
459 - if ( node === this[i] ) {
460 - return offset;
461 - }
462 - if ( this[i].length ) {
463 - var childOffset = es.DocumentModel.prototype.getOffsetFromNode.call( this[i], node );
464 - if ( childOffset !== -1 ) {
465 - return offset + childOffset;
 455+ var offset = 0,
 456+ currentNode,
 457+ iteration = [this, 0],
 458+ iterations = [iteration];
 459+ while ( iterations[0][0].length < iteration[0][1] ) {
 460+ currentNode = iteration[0][iteration[1]];
 461+ if ( currentNode === node ) {
 462+ break;
 463+ } else {
 464+ if ( currentNode.length ) {
 465+ // Include opening element when descending
 466+ offset++;
 467+ // Descend one level down
 468+ iterations.push( [currentNode, 0] );
 469+ iteration = iterations[iterations.length - 1];
 470+ } else {
 471+ // Include opening and closing when passing over
 472+ offset += 2;
466473 }
467474 }
468 - offset += this[i].getElementLength();
 475+ iteration[1]++;
 476+ if ( iteration[1] >= iteration[0].length ) {
 477+ // Include closing element when ascending
 478+ offset++;
 479+ // Ascend one level up
 480+ iterations.pop();
 481+ iteration = iterations[iterations.length - 1];
 482+ }
469483 }
470 - return -1;
 484+ return offset;
471485 };
472486
473487 /**

Status & tagging log