From 587a5fbcbb61f83270fc102da47615b8ff64351c Mon Sep 17 00:00:00 2001 From: Sindre Sorhus Date: Wed, 26 Dec 2018 02:37:03 +0100 Subject: [PATCH] Code style tweaks --- index.js | 50 +++++++++++++++++++------------------------------- templates.js | 40 ++++++++++++++++++++++------------------ 2 files changed, 41 insertions(+), 49 deletions(-) diff --git a/index.js b/index.js index b77dfbb..73598be 100644 --- a/index.js +++ b/index.js @@ -1,8 +1,7 @@ 'use strict'; const escapeStringRegexp = require('escape-string-regexp'); const ansiStyles = require('ansi-styles'); -const stdoutColor = require('supports-color').stdout; - +const {stdout: stdoutColor} = require('supports-color'); const template = require('./templates.js'); const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); @@ -15,15 +14,15 @@ const skipModels = new Set(['gray']); const styles = Object.create(null); -function applyOptions(obj, options = {}) { +function applyOptions(object, options = {}) { if (options.level > 3 || options.level < 0) { throw new Error('The `level` option should be an integer from 0 to 3'); } // Detect level if not set manually - const scLevel = stdoutColor ? stdoutColor.level : 0; - obj.level = options.level === undefined ? scLevel : options.level; - obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; + const colorLevel = stdoutColor ? stdoutColor.level : 0; + object.level = options.level === undefined ? colorLevel : options.level; + object.enabled = 'enabled' in options ? options.enabled : object.level > 0; } function Chalk(options) { @@ -33,7 +32,7 @@ function Chalk(options) { const chalk = {}; applyOptions(chalk, options); - chalk.template = (...args) => chalkTag(...[chalk.template].concat(args)); + chalk.template = (...args) => chalkTag(chalk.template, ...args); Object.setPrototypeOf(chalk, Chalk.prototype); Object.setPrototypeOf(chalk.template, chalk); @@ -57,7 +56,7 @@ for (const key of Object.keys(ansiStyles)) { styles[key] = { get() { const codes = ansiStyles[key]; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); + return build.call(this, [...(this._styles || []), codes], this._empty, key); } }; } @@ -84,7 +83,7 @@ for (const model of Object.keys(ansiStyles.color.ansi)) { close: ansiStyles.color.close, closeRe: ansiStyles.color.closeRe }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + return build.call(this, [...(this._styles || []), codes], this._empty, model); }; } }; @@ -107,7 +106,7 @@ for (const model of Object.keys(ansiStyles.bgColor.ansi)) { close: ansiStyles.bgColor.close, closeRe: ansiStyles.bgColor.closeRe }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + return build.call(this, [...(this._styles || []), codes], this._empty, model); }; } }; @@ -153,23 +152,10 @@ function build(_styles, _empty, key) { } function applyStyle(...args) { - // Support varags, but simply cast to string in case there's only one arg - const argsLen = args.length; - let str = String(args[0]); + let string = args.join(' '); - if (argsLen === 0) { - return ''; - } - - if (argsLen > 1) { - // Don't slice `arguments`, it prevents V8 optimizations - for (let a = 1; a < argsLen; a++) { - str += ' ' + args[a]; - } - } - - if (!this.enabled || this.level <= 0 || !str) { - return this._empty ? '' : str; + if (!this.enabled || this.level <= 0 || !string) { + return this._empty ? '' : string; } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, @@ -184,18 +170,18 @@ function applyStyle(...args) { // Replace any instances already present with a re-opening code // otherwise only the part of the string until said closing code // will be colored, and the rest will simply be 'plain'. - str = code.open + str.replace(code.closeRe, code.open) + code.close; + string = code.open + string.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen // after next line to fix a bleed issue on macOS // https://github.com/chalk/chalk/pull/92 - str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); + string = string.replace(/\r?\n/g, `${code.close}$&${code.open}`); } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue ansiStyles.dim.open = originalDim; - return str; + return string; } function chalkTag(chalk, ...strings) { @@ -211,8 +197,10 @@ function chalkTag(chalk, ...strings) { const parts = [firstString.raw[0]]; for (let i = 1; i < firstString.length; i++) { - parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); - parts.push(String(firstString.raw[i])); + parts.push( + String(args[i - 1]).replace(/[{}\\]/g, '\\$&'), + String(firstString.raw[i]) + ); } return template(chalk, parts.join('')); diff --git a/templates.js b/templates.js index 1f6c035..bbc614d 100644 --- a/templates.js +++ b/templates.js @@ -31,10 +31,11 @@ function parseArguments(name, args) { let matches; for (const chunk of chunks) { - if (!isNaN(chunk)) { - results.push(Number(chunk)); + const number = Number(chunk); + if (!Number.isNaN(number)) { + results.push(number); } else if ((matches = chunk.match(STRING_REGEX))) { - results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr)); + results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character)); } else { throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); } @@ -73,17 +74,20 @@ function buildStyle(chalk, styles) { } let current = chalk; + // TODO: Use `Object.entries` when targeting Node.js 8 for (const styleName of Object.keys(enabled)) { - if (Array.isArray(enabled[styleName])) { - if (!(styleName in current)) { - throw new Error(`Unknown Chalk style: ${styleName}`); - } + if (!Array.isArray(enabled[styleName])) { + continue; + } - if (enabled[styleName].length > 0) { - current = current[styleName](...enabled[styleName]); - } else { - current = current[styleName]; - } + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } + + if (enabled[styleName].length > 0) { + current = current[styleName](...enabled[styleName]); + } else { + current = current[styleName]; } } @@ -96,13 +100,13 @@ module.exports = (chalk, tmp) => { let chunk = []; // eslint-disable-next-line max-params - tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { - if (escapeChar) { - chunk.push(unescape(escapeChar)); + tmp.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => { + if (escapeCharacter) { + chunk.push(unescape(escapeCharacter)); } else if (style) { - const str = chunk.join(''); + const string = chunk.join(''); chunk = []; - chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); + chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string)); styles.push({inverse, styles: parseStyle(style)}); } else if (close) { if (styles.length === 0) { @@ -113,7 +117,7 @@ module.exports = (chalk, tmp) => { chunk = []; styles.pop(); } else { - chunk.push(chr); + chunk.push(character); } });