diff options
| author | Abigail <abigail@abigail.be> | 2021-03-14 19:52:22 +0100 |
|---|---|---|
| committer | Abigail <abigail@abigail.be> | 2021-03-14 19:59:46 +0100 |
| commit | c8806dd8c6106b70a7d40a794116e879fdbc7d35 (patch) | |
| tree | 9027ea347848e20a1018f71c046aa021298a144a | |
| parent | b4dcb4bf524efdd280f55721a05a4572be32e7c7 (diff) | |
| download | perlweeklychallenge-club-c8806dd8c6106b70a7d40a794116e879fdbc7d35.tar.gz perlweeklychallenge-club-c8806dd8c6106b70a7d40a794116e879fdbc7d35.tar.bz2 perlweeklychallenge-club-c8806dd8c6106b70a7d40a794116e879fdbc7d35.zip | |
Node.js solution for week 103, part 2
| -rw-r--r-- | challenge-103/abigail/README.md | 1 | ||||
| -rw-r--r-- | challenge-103/abigail/node/ch-2.js | 69 |
2 files changed, 70 insertions, 0 deletions
diff --git a/challenge-103/abigail/README.md b/challenge-103/abigail/README.md index 69c67fa04e..b645561bf2 100644 --- a/challenge-103/abigail/README.md +++ b/challenge-103/abigail/README.md @@ -127,6 +127,7 @@ Output: * [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) * [Python](python/ch-2.py) * [Ruby](ruby/ch-2.rb) diff --git a/challenge-103/abigail/node/ch-2.js b/challenge-103/abigail/node/ch-2.js new file mode 100644 index 0000000000..31ed400038 --- /dev/null +++ b/challenge-103/abigail/node/ch-2.js @@ -0,0 +1,69 @@ +#!/usr/local/bin/node + +// +// See ../README.md +// + +// +// Run as: node ch-2.js < input-file +// + +const fs = require ('fs') +const readline = require ('readline') +const printf = require ('printf') + +readline . createInterface ({input: process . stdin}) + . on ('line', _ => main (... _ . split (" "))) + +function main (start_time, current_time, file_name) { + let time_diff = (current_time - start_time) * 1000; + + // + // Read in the media file, into an array tracks. + // Calculate the total time of playing all the tracks. + // + let tracks = require ("fs") . readFileSync (file_name) + . toString () + . split ("\n") + . filter (_ => _ . length) + . map (_ => _ . split (",", 2)) + . map (_ => [+_ [0], _ [1]]) + let total_time = 0; + tracks . forEach (_ => total_time += _ [0]) + + // + // Don't care about full loops + // + time_diff %= total_time + + // + // Find the right track and print it. + // + done = 0 + tracks . forEach (track => { + if (!done) { + if (time_diff - track [0] < 0) { + console . log (track [1]) + time_diff = Math . floor (time_diff / 1000) + let hours = Math . floor (time_diff / 3600) + let minutes = Math . floor ((time_diff % 3600) / 60) + let seconds = time_diff % 60 + + if (hours > 0) { + console . log ( + printf ("%02d:%02d:%02d", hours, minutes, seconds) + ) + } + else { + console . log ( + printf ( "%02d:%02d", minutes, seconds) + ) + } + done = 1 // There's no 'break' when using forEach + } + else { + time_diff -= track [0] + } + } + }) +} |
