Skip to content

Instantly share code, notes, and snippets.

@MikeBild

MikeBild/coin-changer.js

Last active Oct 29, 2016
Embed
What would you like to do?
Resource lifetime binding to RxJS stream
const Rx = require('rx');
const coinsStream = Rx.Observable.fromArray([1,2,5,10,20,50,100].reverse());
Rx.Observable
// bind CoinResource lifetime to the stream lifetime
.using(() => new CoinResource(9), resource => coinsStream.map(x => ({ amount: resource.getValue(), coin: x })))
// calculations
.reduce((state, e) => {
const amount = (state.length > 0) ? state[state.length-1].rest : e.amount;
state.push({
coin: e.coin,
number: Math.floor(amount/e.coin),
rest: amount%e.coin,
});
return state;
}, [])
// debug
.do(x => console.log(JSON.stringify(x)))
.subscribe();
function CoinResource(value) {
this.value = value;
this.disposed = false;
this.getValue = () => {
if (this.disposed) throw new Error('Object is disposed');
return this.value;
};
this.dispose = () => {
// release resource
if (!this.disposed) {
this.disposed = true;
this.value = null;
}
};
}
@CarstenKoenig

This comment has been minimized.

Copy link

@CarstenKoenig CarstenKoenig commented Oct 29, 2016

Nice one - although I would probably move out the rest from all the accumulated results and lift it into a (rest, picks) tuple

This way you don't have to index the array and don't need to ? .. : ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.