Skip to content

Commit

Permalink
cache isArray, test for automatic casting
Browse files Browse the repository at this point in the history
  • Loading branch information
toonijn committed Jun 8, 2020
1 parent 2451677 commit 26c73d2
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
6 changes: 4 additions & 2 deletions source/index.js
Expand Up @@ -6,6 +6,8 @@ const {
stringEncaseCRLFWithFirstIndex
} = require('./util');

const {isArray} = Array;

// `supportsColor.level` → `ansiStyles.color[name]` mapping
const levelMapping = [
'ansi',
Expand Down Expand Up @@ -134,7 +136,7 @@ const createStyler = (open, close, parent) => {

const createBuilder = (self, _styler, _isEmpty) => {
const builder = (...arguments_) => {
if (Array.isArray(arguments_[0])) {
if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) {
// Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
return applyStyle(builder, chalkTag(builder, ...arguments_));
}
Expand Down Expand Up @@ -193,7 +195,7 @@ let template;
const chalkTag = (chalk, ...strings) => {
const [firstString] = strings;

if (!Array.isArray(firstString)) {
if (!isArray(firstString) || !isArray(firstString.raw)) {
// If chalk() was called by itself or with a string,
// return the string itself as a string.
return strings.join(' ');
Expand Down
8 changes: 8 additions & 0 deletions test/chalk.js
Expand Up @@ -16,6 +16,14 @@ test('support multiple arguments in base function', t => {
t.is(chalk('hello', 'there'), 'hello there');
});

test('support automatic casting to string', t => {
t.is(chalk(['hello', 'there']), 'hello,there');
t.is(chalk(123), '123');

t.is(chalk.bold(['foo', 'bar']), '\u001B[1mfoo,bar\u001B[22m');
t.is(chalk.green(98765), '\u001B[32m98765\u001B[39m');
});

test('style string', t => {
t.is(chalk.underline('foo'), '\u001B[4mfoo\u001B[24m');
t.is(chalk.red('foo'), '\u001B[31mfoo\u001B[39m');
Expand Down
5 changes: 5 additions & 0 deletions test/template-literal.js
Expand Up @@ -42,6 +42,11 @@ test('correctly perform nested template substitutions', t => {

t.is(instance.strikethrough.cyanBright.bgBlack`Works with {reset {bold numbers}} {bold.red ${1}}`,
instance.strikethrough.cyanBright.bgBlack('Works with ' + instance.reset.bold('numbers') + ' ' + instance.bold.red(1)));

t.is(chalk.bold`Also works on the shared {bgBlue chalk} object`,
'\u001B[1mAlso works on the shared \u001B[1m' +
'\u001B[44mchalk\u001B[49m\u001B[22m' +
'\u001B[1m object\u001B[22m');
});

test('correctly parse and evaluate color-convert functions', t => {
Expand Down

0 comments on commit 26c73d2

Please sign in to comment.