diff options
Diffstat (limited to 'util')
-rw-r--r-- | util/count.js | 17 | ||||
-rw-r--r-- | util/smoothen.js | 16 | ||||
-rw-r--r-- | util/wrap.js | 22 |
3 files changed, 55 insertions, 0 deletions
diff --git a/util/count.js b/util/count.js new file mode 100644 index 0000000..7df97a7 --- /dev/null +++ b/util/count.js @@ -0,0 +1,17 @@ +module.exports = function count(arr) { + // Counts the number of times the items of an array appear (only on the top + // level; it doesn't search through nested arrays!). Returns a map of + // item -> count. + + const map = new Map() + + for (let item of arr) { + if (map.has(item)) { + map.set(item, map.get(item) + 1) + } else { + map.set(item, 1) + } + } + + return map +} diff --git a/util/smoothen.js b/util/smoothen.js new file mode 100644 index 0000000..55ba23c --- /dev/null +++ b/util/smoothen.js @@ -0,0 +1,16 @@ +module.exports = function(tx, x, divisor) { + // Smoothly transitions givens X to TX using a given divisor. Rounds the + // amount moved. + + const move = (tx - x) / divisor + + if (move > 0.5) { + return x + Math.ceil(move) + } else if (move < -0.5) { + return x + Math.floor(move) + } else if (tx > 0) { + return Math.ceil(tx) + } else { + return Math.floor(tx) + } +} diff --git a/util/wrap.js b/util/wrap.js new file mode 100644 index 0000000..78e5233 --- /dev/null +++ b/util/wrap.js @@ -0,0 +1,22 @@ +module.exports = function wrap(str, width) { + // Wraps a string into separate lines. Returns an array of strings, for + // each line of the text. + + const lines = [] + const words = str.split(' ') + + let curLine = words[0] + + for (let word of words.slice(1)) { + if (curLine.length + word.length > width) { + lines.push(curLine) + curLine = word + } else { + curLine += ' ' + word + } + } + + lines.push(curLine) + + return lines +} |