02. Depositing schmeckels
May 30, 2018 ยท View on GitHub
Congratulations on passing problem 01. As you probably noticed the bank so far doesn't do much, so let's try and expand the functionality a bit. Pinky promise we'll get to the crypto soon!
Solution to problem 01
// bank.js
var jsonStream = require('duplex-json-stream')
var net = require('net')
var server = net.createServer(function (socket) {
socket = jsonStream(socket)
socket.on('data', function (msg) {
console.log('Bank received:', msg)
socket.write({cmd: 'balance', balance: 0})
})
})
server.listen(3876)
// 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)
})
client.end({cmd: 'balance'})
Tracking transactions
Next you should add a deposit command, which takes an amount and adds this
to the bank vault balance. But to keep an audit trail all deposits should be
kept in a transaction log. This will prove to have lots of benefits later. A
transaction log is just another way of saying that all operations that modify
the state are kept in an array, and the current state is derived by .reduceing
this array.
For example, here's a transaction log that should reduce to balance of 250 schmeckels:
var log = [
{cmd: 'deposit', amount: 130},
{cmd: 'deposit', amount: 0},
{cmd: 'deposit', amount: 120}
]
Side quest
As an optional exercise, try writing a .reduce
function that takes the above log, and arrives at the correct balance. To test
it out, try adding more entries to the log.
Problem
You job now is to expand the teller.js and bank.js with the deposit
command, that is stored in a transaction log and updates the bank state (ie.
it's balance). When the bank gets a deposit command, it should reply with the
current balance like this: {cmd: 'balance', balance: someNumber}.
A good idea is to make teller.js a very simple CLI tool, reading commands and
arguments from process.argv.
Hint
You can easily handle multiple commands using a switch statement like this:
switch (command) {
case 'balance':
// ...
break
case 'deposit':
// ...
break
default:
// Unknown command
break
}
Testing
Spin up your new bank.js to make a couple of deposit up to 250 schmeckels in
your bank, using node teller.js deposit 123, and checking your balance.