Improve performance for generator.buffer

This commit is contained in:
Jason
2016-01-20 02:01:41 +08:00
parent 235d8397fd
commit 993c5a572b

View File

@@ -14,6 +14,7 @@ export default class Buffer {
this._indent = format.indent.base;
this.format = format;
this.buf = "";
this.last = "";
}
parenPushNewlineState: ?Object;
@@ -191,42 +192,24 @@ export default class Buffer {
return;
}
removeLast = removeLast || false;
if (typeof i === "number") {
i = Math.min(2, i);
if (this.endsWith("{\n") || this.endsWith(":\n")) i--;
if (i <= 0) return;
while (i > 0) {
this._newline(removeLast);
i--;
}
return;
}
if (typeof i === "boolean") {
removeLast = i;
}
this._newline(removeLast);
}
/**
* Adds a newline unless there is already two previous newlines.
*/
_newline(removeLast?: boolean) {
// never allow more than two lines
if (this.endsWith("\n\n")) return;
if (typeof i === "boolean") removeLast = i;
if (typeof i !== "number") i = 1;
i = Math.min(2, i);
if (this.endsWith("{\n") || this.endsWith(":\n")) i--;
if (i <= 0) return;
// remove the last newline
if (removeLast && this.isLast("\n")) this.removeLast("\n");
if (removeLast) {
this.removeLast("\n");
}
this.removeLast(" ");
this._removeSpacesAfterLastNewline();
this._push("\n");
this._push(repeating("\n", i));
}
/**
@@ -235,21 +218,8 @@ export default class Buffer {
_removeSpacesAfterLastNewline() {
let lastNewlineIndex = this.buf.lastIndexOf("\n");
if (lastNewlineIndex === -1) {
return;
}
let index = this.buf.length - 1;
while (index > lastNewlineIndex) {
if (this.buf[index] !== " ") {
break;
}
index--;
}
if (index === lastNewlineIndex) {
this.buf = this.buf.substring(0, index + 1);
if (lastNewlineIndex >= 0 && this.buf.trimRight().length <= lastNewlineIndex) {
this.buf = this.buf.substring(0, lastNewlineIndex + 1);
this.last = "\n";
}
}
@@ -310,11 +280,11 @@ export default class Buffer {
* Test if the buffer ends with a string.
*/
endsWith(str: string, buf: string = this.buf): boolean {
endsWith(str: string): boolean {
if (str.length === 1) {
return buf[buf.length - 1] === str;
return this.last === str;
} else {
return buf.slice(-str.length) === str;
return this.buf.slice(-str.length) === str;
}
}