chalk/examples/rainbow.js

39 lines
841 B
JavaScript
Raw Normal View History

2017-06-30 12:42:24 +02:00
'use strict';
2017-06-29 16:00:51 -07:00
const chalk = require('..');
const ignoreChars = /[^!-~]/;
function rainbow(str, offset) {
if (!str || str.length === 0) {
return str;
}
const hueStep = 360 / str.replace(ignoreChars, '').length;
let hue = offset % 360;
const chars = [];
for (const c of str) {
if (c.match(ignoreChars)) {
chars.push(c);
} else {
chars.push(chalk.hsl(hue, 100, 50)(c));
hue = (hue + hueStep) % 360;
}
}
return chars.join('');
}
2017-06-30 12:42:24 +02:00
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
2017-06-29 16:00:51 -07:00
async function animateString(str) {
console.log();
2017-06-29 16:05:28 -07:00
for (let i = 0; i < 360 * 5; i++) {
2017-06-30 12:42:24 +02:00
console.log('\u001B[1F\u001B[G ', rainbow(str, i));
await sleep(2); // eslint-disable-line no-await-in-loop
2017-06-29 16:00:51 -07:00
}
}
console.log();
animateString('We hope you enjoy the new version of Chalk 2! <3').then(() => console.log());