Speed up common case where consumer moves only forward

This commit is contained in:
Dan Abramov 2015-01-14 20:02:40 +03:00
parent c7c90acf3f
commit 19eaa181a5

View File

@ -3,9 +3,22 @@ module.exports = Whitespace;
var _ = require("lodash");
var util = require("../util");
// a helper to iterate array from arbitrary index
function getLookupIndex(i, base, max) {
i += base;
if (i >= max)
i -= max;
return i;
}
function Whitespace(tokens, comments) {
this.tokens = _.sortBy(tokens.concat(comments), "start");
this.used = [];
// speed up common case where methods are called for next tokens
this._lastFoundIndex = 0;
}
Whitespace.prototype.getNewlinesBefore = function (node) {
@ -14,13 +27,15 @@ Whitespace.prototype.getNewlinesBefore = function (node) {
var tokens = this.tokens;
var token;
for (var i = 0; i < tokens.length; i++) {
for (var j = 0; j < tokens.length; j++) {
var i = getLookupIndex(j, this._lastFoundIndex, this.tokens.length);
token = tokens[i];
// this is the token this node starts with
if (node.start === token.start) {
startToken = tokens[i - 1];
endToken = token;
this._lastFoundIndex = i;
break;
}
}
@ -34,13 +49,15 @@ Whitespace.prototype.getNewlinesAfter = function (node) {
var tokens = this.tokens;
var token;
for (var i = 0; i < tokens.length; i++) {
for (var j = 0; j < tokens.length; j++) {
var i = getLookupIndex(j, this._lastFoundIndex, this.tokens.length);
token = tokens[i];
// this is the token this node ends with
if (node.end === token.end) {
startToken = token;
endToken = tokens[i + 1];
this._lastFoundIndex = i;
break;
}
}