blob: d7086b3b8f8e01a2d607840ed132a415c4029579 (
plain)
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
#!/usr/local/bin/node
//
// See https://theweeklychallenge.org/blog/perl-weekly-challenge-002
//
//
// Run as: node ch-2.js {-f | -t} < input-file
//
// -f: Translate from base 35 to base 10
// -t: Translate to base 35 from base 10
//
let BASE = 35
//
// Parse options using the yargs module
//
const argv = require ('yargs')
. option ('from_base', {
alias: 'f',
type: 'boolean',
})
. option ('to_base', {
alias: 't',
type: 'boolean',
})
. argv;
//
// Check options
//
if ((argv . to_base ? 1 : 0) + (argv . from_base ? 1 : 0) != 1) {
console . log ("Requires exactly one of '-f' or '-t'")
process . exit (1)
}
//
// Set up digits, mapping base-10 numbers to base-35 digits, and vice versa
//
let digits = {};
for (let i = 0; i < 10; i ++) {
digits [i] = i
}
for (let i = 10; i < BASE; i ++) {
let char = String . fromCharCode (65 + i - 10)
digits [char] = i
digits [i] = char
}
//
// Translate to base 35
//
function to_base (number) {
let out = "";
while (number) {
let n = number % BASE
out = digits [n] + out
number = Math . floor (number / BASE)
}
return out
}
//
// Translate from base 35
//
function from_base (base) {
let out = 0
base . split ('') . forEach (c => {
out = BASE * out + digits [c]
})
return out
}
//
// Iterate over the input, call either to_base or from_base for each
// line, depending on the -f or -t parameter.
//
require ('readline')
. createInterface ({input: process . stdin})
. on ('line', _ => console . log (argv . to_base ? to_base (+ _)
: from_base (_ . trim ())))
;
|