reorder-cli
Version:
A NodeJS CLI list reorder-er
40 lines (34 loc) • 1.18 kB
JavaScript
const readlineSync = require('readline-sync')
/**
* @param {string[]} list list of any length to reorder.
* @return {Array}
*/
module.exports = function reorderCLI(list) {
let key, index = 0;
console.log('\nUP:[W] DOWN:[S] HOLD:[SHIFT] DONE:[SPACE]' + '\n'.repeat(list.length + 1));
while (true) {
list = getSelected(list, index)
console.log('\x1B[1A\x1B[K'.repeat(list.length) + list.join('\n'));
key = readlineSync.keyIn('', { hideEchoBack: true, mask: '', limit: 'wsWS ' });
if (key.toLowerCase() == 'w') {
if (key.toUpperCase() === key) {
[list[index - 1], list[index]] = [list[index], list[index - 1]]
}
if (index > 0) index--
}
else if (key.toLowerCase() == 's') {
if (key.toUpperCase() === key) {
[list[index], list[index + 1]] = [list[index + 1], list[index]]
}
if (index < list.length - 1) index++
}
else {
break;
}
}
return list.map(val => val.replace(/\u001b.../g, ''))
}
const getSelected = (list, index) => {
list = list.map(val => val.replace(/\u001b.../g, ''))
return list.map((val, i) => (i === index) ? '\x1B[1m' + val + '\x1B[0m' : val)
}