-
Notifications
You must be signed in to change notification settings - Fork 1
/
repl.js
62 lines (50 loc) · 1.35 KB
/
repl.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*eslint no-console: "off"*/
import * as ReadLine from 'readline'
const Chalk = require('chalk')
import * as ColorMath from './src'
const {LessEvaluator, CoreEvaluator} = ColorMath.Evaluators
const lessEval = new LessEvaluator()
const rl = ReadLine.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false,
})
rl.setPrompt('> ')
rl.prompt()
rl
.on('line', (line) => {
const flags = {withAst: false, less: false}
line = parseFlags(line, flags)
if (line) {
const res = ColorMath.evaluate(line, {
evaluator: flags.less ? lessEval : CoreEvaluator.instance,
withAst: flags.withAst,
})
if (res.error != null) {
console.log(Chalk.red(`\n${res.error}\n`))
} else if (flags.withAst) {
console.log(`\n${res.astStr}\n`)
} else {
console.log(`= ${res.resultStr}\n`)
}
}
rl.prompt()
})
.on('close', () => {
process.exit(0)
})
function parseFlags(line, dict) {
let i = 0
const keys = Object.keys(dict)
while (i < keys.length) {
const key = keys[i]
const lineNext = line.replace(new RegExp(`^\\s*${key}\\s+`, 'i'), '')
if (lineNext !== line) {
line = lineNext
dict[key] = true
keys.splice(i, 1)
i = 0
} else {i++}
}
return line
}