diff options
| author | Abigail <abigail@abigail.be> | 2020-12-09 00:59:50 +0100 |
|---|---|---|
| committer | Abigail <abigail@abigail.be> | 2020-12-09 00:59:50 +0100 |
| commit | 78693d44fa0ca444bba777bc68d5f2cd01fbaa1a (patch) | |
| tree | 30b217e0dcd6904406269a4343c9e5b412b7d25f | |
| parent | 706f84cccdb1b5191fbb12c07cfa605d7d9cf7d1 (diff) | |
| download | perlweeklychallenge-club-78693d44fa0ca444bba777bc68d5f2cd01fbaa1a.tar.gz perlweeklychallenge-club-78693d44fa0ca444bba777bc68d5f2cd01fbaa1a.tar.bz2 perlweeklychallenge-club-78693d44fa0ca444bba777bc68d5f2cd01fbaa1a.zip | |
Node.js solution for week 90/part 2
| -rw-r--r-- | challenge-090/abigail/README.md | 1 | ||||
| -rw-r--r-- | challenge-090/abigail/node/ch-2.js | 48 |
2 files changed, 49 insertions, 0 deletions
diff --git a/challenge-090/abigail/README.md b/challenge-090/abigail/README.md index 546ac5f46d..c89a14792e 100644 --- a/challenge-090/abigail/README.md +++ b/challenge-090/abigail/README.md @@ -42,4 +42,5 @@ Write a script to demonstrate ## Solutions * [C](c/ch-2.c) +* [Node.js](node/ch-2.js) * [Perl](perl/ch-2.pl) diff --git a/challenge-090/abigail/node/ch-2.js b/challenge-090/abigail/node/ch-2.js new file mode 100644 index 0000000000..4850a5f722 --- /dev/null +++ b/challenge-090/abigail/node/ch-2.js @@ -0,0 +1,48 @@ +let indent = " "; +let line = indent . replace (/ /g, "-"); +let spacing = " "; + +// +// Read STDIN. Split on newlines, filter out empty lines, +// split each line on white space, then call "show" +// + require ("fs") +. readFileSync (0) // Read all. +. toString () // Turn it into a string. +. split ("\n") // Split on newlines. +. filter (_ => _ . length) // Filter out empty lines. +. map (_ => _ . split (/\s+/)) +. map (_ => show (_ [0], _ [1])) +; + +// +// Return a number, padded with space to the required width. +// If width is less than the length of n, bad things may happen. +// +function format_n (n, width) { +// return (indent + n) . substr (-width); + return (" " + n) . substr (-width); +} + +// +// Do the main work +// +function show (A, B) { + let P = A * B; + let w_A = ("" + A) . length; + let w_P = ("" + P) . length; + let tick = String . fromCodePoint (0x2713); + + while (A) { + process . stdout . write (format_n (A, w_A) + spacing + + format_n (B, w_P) + " " + + (A % 2 ? tick : "") + "\n"); + A = Math . floor (A / 2); + B = B * 2; + } + + process . stdout . write (indent . substr (-w_A) + spacing + + line . substr (-w_P) + " +\n"); + process . stdout . write (indent . substr (-w_A) + spacing + + P + "\n"); +} |
