From 6c4da7fac6ea909adac1be00e238d213e84c0ec6 Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Sun, 26 Apr 2020 18:15:15 -0600 Subject: add trading in the rain post --- assets/trading-in-the-rain/Distributor.js | 42 +++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 assets/trading-in-the-rain/Distributor.js (limited to 'assets/trading-in-the-rain/Distributor.js') diff --git a/assets/trading-in-the-rain/Distributor.js b/assets/trading-in-the-rain/Distributor.js new file mode 100644 index 0000000..fa6e9f2 --- /dev/null +++ b/assets/trading-in-the-rain/Distributor.js @@ -0,0 +1,42 @@ +function distribute(val, minOld, maxOld, minNew, maxNew) { + let scalar = (val - minOld) / (maxOld - minOld); + return minNew + ((maxNew - minNew) * scalar); +} + +function Distributor(capacity) { + this.cap = capacity; + + this.reset = () => { + this.arr = []; + this.arrSorted = []; + this.length = 0; + }; + this.reset(); + + // add adds the given value into the series, shifting off the oldest value if + // the series is at capacity. + this.add = (val) => { + this.arr.push(val); + if (this.arr.length >= this.cap) this.arr.shift(); + this.arrSorted = this.arr.slice(); // copy array + this.arrSorted.sort(); + this.length = this.arr.length; + }; + + // distribute finds where the given value falls within the series, and then + // scales that into the given range (inclusive). + this.distribute = (val, min, max) => { + if (this.length == 0) throw "cannot locate within empty Distributor"; + + let idx = this.length; + for (i in this.arrSorted) { + if (val < this.arrSorted[i]) { + idx = i; + break; + } + } + + return distribute(idx, 0, this.length, min, max); + }; +} + -- cgit v1.2.3