chalk/examples/rainbow.js

39 lines
926 B
JavaScript
Raw Normal View History

import convertColor from 'color-convert';
import updateLog from 'log-update';
import delay from 'yoctodelay';
import chalk from '../source/index.js';
2017-06-29 16:00:51 -07:00
const ignoreChars = /[^!-~]/g;
2017-06-29 16:00:51 -07:00
2019-03-12 20:11:31 +07:00
function rainbow(string, offset) {
if (!string || string.length === 0) {
return string;
2017-06-29 16:00:51 -07:00
}
2019-03-12 20:11:31 +07:00
const hueStep = 360 / string.replace(ignoreChars, '').length;
2017-06-29 16:00:51 -07:00
let hue = offset % 360;
2019-03-12 20:11:31 +07:00
const characters = [];
for (const character of string) {
2021-04-16 15:23:29 +07:00
if (ignoreChars.test(character)) {
2019-03-12 20:11:31 +07:00
characters.push(character);
2017-06-29 16:00:51 -07:00
} else {
characters.push(chalk.hex(convertColor.hsl.hex(hue, 100, 50))(character));
2017-06-29 16:00:51 -07:00
hue = (hue + hueStep) % 360;
}
}
2019-03-12 20:11:31 +07:00
return characters.join('');
2017-06-29 16:00:51 -07:00
}
2019-03-12 20:11:31 +07:00
async function animateString(string) {
2021-04-16 15:23:29 +07:00
for (let index = 0; index < 360 * 5; index++) {
updateLog(rainbow(string, index));
2019-03-12 20:11:31 +07:00
await delay(2); // eslint-disable-line no-await-in-loop
2017-06-29 16:00:51 -07:00
}
}
2022-11-17 01:56:01 +07:00
console.log();
await animateString('We hope you enjoy Chalk! <3');
console.log();