Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

solution proposal 4 #30

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions problems/05.md
Original file line number Diff line number Diff line change
Expand Up @@ -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, null, 2);
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")


```

Expand Down