From db05bd869a464e6656e759c6f422717175eebcc8 Mon Sep 17 00:00:00 2001 From: Abigail Date: Thu, 1 Apr 2021 18:00:02 +0200 Subject: Node.js solution for week 106, part 2 --- challenge-106/abigail/README.md | 1 + challenge-106/abigail/node/ch-2.js | 40 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 challenge-106/abigail/node/ch-2.js diff --git a/challenge-106/abigail/README.md b/challenge-106/abigail/README.md index e3278d4b6d..8caecfeacd 100644 --- a/challenge-106/abigail/README.md +++ b/challenge-106/abigail/README.md @@ -96,6 +96,7 @@ Wikipedia](https://en.wikipedia.org/wiki/Repeating_decimal). * [Bash](bash/ch-2.sh) * [C](c/ch-2.c) * [Lua](lua/ch-2.lua) +* [Node.js](node/ch-2.js) * [Perl](perl/ch-2.pl) ### Blog diff --git a/challenge-106/abigail/node/ch-2.js b/challenge-106/abigail/node/ch-2.js new file mode 100644 index 0000000000..166a3e050e --- /dev/null +++ b/challenge-106/abigail/node/ch-2.js @@ -0,0 +1,40 @@ +#!/usr/local/bin/node + +// +// See ../README.md +// + +// +// Run as: node ch-2.js < input-file +// + +require ('readline') +. createInterface ({input: process . stdin}) +. on ('line', _ => console . log (long_division (... _ . split (" ") + . map (_ => +_)))) + +// +// See ../README.md for info about this function +// + +function long_division (numerator, denominator) { + let BASE = 10 + let fraction = Math . floor (numerator / denominator) + "." + let position = fraction . length + let seen = [] + + numerator %= denominator + + while (!(numerator in seen)) { + if (!numerator) { + return (fraction) + } + seen [numerator] = position + fraction += Math . floor (BASE * numerator / denominator) + numerator = BASE * numerator % denominator + position ++ + } + + return (fraction . substr (0, seen [numerator]) + "(" + + fraction . substr ( seen [numerator]) + ")") +} -- cgit