diff --git a/src/babel/generation/buffer.js b/src/babel/generation/buffer.js index 3902f64577..2b86094fdb 100644 --- a/src/babel/generation/buffer.js +++ b/src/babel/generation/buffer.js @@ -3,6 +3,7 @@ import trimRight from "trim-right"; import isBoolean from "lodash/lang/isBoolean"; import includes from "lodash/collection/includes"; import isNumber from "lodash/lang/isNumber"; +import * as t from "../types"; export default class Buffer { constructor(position, format) { @@ -54,9 +55,10 @@ export default class Buffer { this.space(); } - space() { - if (this.format.compact) return; - if (this.buf && !this.isLast(" ") && !this.isLast("\n")) { + space(force?) { + if (!force && this.format.compact) return; + + if (force || this.buf && !this.isLast(" ") && !this.isLast("\n")) { this.push(" "); } } @@ -155,8 +157,12 @@ export default class Buffer { this.buf += str; } - endsWith(str) { - return this.buf.slice(-str.length) === str; + endsWith(str, buf = this.buf) { + if (str.length === 1) { + return buf[buf.length - 1] === str; + } else { + return buf.slice(-str.length) === str; + } } isLast(cha) { diff --git a/src/babel/generation/generators/expressions.js b/src/babel/generation/generators/expressions.js index da376d76a0..8cb31db609 100644 --- a/src/babel/generation/generators/expressions.js +++ b/src/babel/generation/generators/expressions.js @@ -2,19 +2,19 @@ import isNumber from "lodash/lang/isNumber"; import * as t from "../../types"; export function UnaryExpression(node, print) { - var hasSpace = /[a-z]$/.test(node.operator); + var needsSpace = /[a-z]$/.test(node.operator); var arg = node.argument; if (t.isUpdateExpression(arg) || t.isUnaryExpression(arg)) { - hasSpace = true; + needsSpace = true; } if (t.isUnaryExpression(arg) && arg.operator === "!") { - hasSpace = false; + needsSpace = false; } this.push(node.operator); - if (hasSpace) this.push(" "); + if (needsSpace) this.push(" "); print.plain(node.argument); } @@ -83,19 +83,16 @@ export function CallExpression(node, print) { this.push("("); - var separator = ","; - - var isPrettyCall = node._prettyCall && !this.format.retainLines; + var isPrettyCall = node._prettyCall && !this.format.retainLines && !this.format.compact; + var separator; if (isPrettyCall) { - separator += "\n"; + separator = ",\n"; this.newline(); this.indent(); - } else { - separator += " "; } - print.list(node.arguments, { separator: separator }); + print.list(node.arguments, { separator }); if (isPrettyCall) { this.newline(); @@ -141,9 +138,22 @@ export function AssignmentPattern(node, print) { export function AssignmentExpression(node, print) { // todo: add cases where the spaces can be dropped when in compact mode print.plain(node.left); - this.push(" "); + + var spaces = node.operator === "in" || node.operator === "instanceof"; + this.space(spaces); + this.push(node.operator); - this.push(" "); + + if (!spaces) { + // space is mandatory to avoid outputting