From 2c283503a46777606e12ee67f3da38bd427b96ed Mon Sep 17 00:00:00 2001 From: Simon El Nahas Christensen Date: Sun, 21 Jul 2019 01:27:28 +0200 Subject: [PATCH 1/2] solution proposal 4 --- problems/05.md | 89 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) diff --git a/problems/05.md b/problems/05.md index c63604a..f818124 100644 --- a/problems/05.md +++ b/problems/05.md @@ -9,11 +9,100 @@ we can secure our bank. ```js // bank.js +var jsonStream = require('duplex-json-stream') +var net = require('net') +var fs = require('fs') +var log = require('./log.json') + +function sum() { + return log.reduce( + function (accu, x) { + switch (x.cmd) { + case 'deposit': + return accu + x.amount + case 'withdraw': + return accu - x.amount + default: + return accu + } + } + , 0) +} + +function save() { + let data = JSON.stringify(log); + fs.writeFileSync('log.json', data); +} + + +var server = net.createServer(function (socket) { + socket = jsonStream(socket) + socket.on('data', function (msg) { + console.log('Bank received:', msg) + let amount = Math.abs(parseInt(msg.amount)) + switch (msg.cmd){ + case 'balance': + socket.write({ cmd: 'balance', balance: sum() }) + break + case 'deposit': + log.push({cmd: 'deposit', amount: amount}) + save() + socket.write({ cmd: 'balance', balance: sum() }) + break + case 'withdraw': + if(amount<=sum()){ + log.push({cmd: 'withdraw', amount: amount}) + save() + socket.write({ cmd: 'balance', balance: sum() }) + } else { + socket.write("insufficient funds") + } + break + default: + break + } + + }) +}) + +server.listen(3876) + +console.log("started bank") + ``` ```js // teller.js +var jsonStream = require('duplex-json-stream') +var net = require('net') + +var client = jsonStream(net.connect(3876)) + +client.on('data', function (msg) { + console.log('Teller received:', msg) +}) + +const args = process.argv.slice(2) +const command = args[0] +const amount = Math.abs(parseInt(args[1])) + +switch (command){ + case 'balance': + client.end({cmd: 'balance'}) + break + case 'deposit': + client.end({cmd: 'deposit', amount: amount}) + break + case 'withdraw': + client.end({cmd: 'withdraw', amount: amount}) + break + default: + break +} + +console.log("started teller") + ``` From 2df9981e9dfaf52c7e6b21d27c63631b9cf4104a Mon Sep 17 00:00:00 2001 From: Simon El Nahas Christensen Date: Sun, 21 Jul 2019 01:58:20 +0200 Subject: [PATCH 2/2] Update 05.md --- problems/05.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/05.md b/problems/05.md index f818124..4e6d933 100644 --- a/problems/05.md +++ b/problems/05.md @@ -30,7 +30,7 @@ function sum() { } function save() { - let data = JSON.stringify(log); + let data = JSON.stringify(log, null, 2); fs.writeFileSync('log.json', data); }