diff options
author | Brian Picciano <mediocregopher@gmail.com> | 2021-01-21 17:22:53 -0700 |
---|---|---|
committer | Brian Picciano <mediocregopher@gmail.com> | 2021-01-21 17:22:53 -0700 |
commit | bcf9b230be6d74c71567fd0771b31d47d8dd39c7 (patch) | |
tree | 2d0fc16142d55bbd5876ac6b8174c2857883b40e /src/assets/trading-in-the-rain/Distributor.js | |
parent | d57fd70640948cf20eeb41b56e8d4e23e616cec0 (diff) |
build the blog with nix
Diffstat (limited to 'src/assets/trading-in-the-rain/Distributor.js')
-rw-r--r-- | src/assets/trading-in-the-rain/Distributor.js | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/src/assets/trading-in-the-rain/Distributor.js b/src/assets/trading-in-the-rain/Distributor.js new file mode 100644 index 0000000..fa6e9f2 --- /dev/null +++ b/src/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); + }; +} + |