Created
January 27, 2023 09:16
-
-
Save jurca/80494cb5ed42fcdc9114dd373450cd2b to your computer and use it in GitHub Desktop.
Generator of ASCII-style column graphs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Generates an ASCII-style (using UTF-8 characters) column graph of the provided values. | |
* | |
* @param {number[]} data The values to graph as columns. Each value will be represented by a single column in the graph. | |
* @param {number} minY The lower bound of the Y axis. | |
* @param {number} maxY The upper bound of the Y axis. | |
* @param {number} scaleY The number of text rows to represent the Y axis. | |
* @return {string} Generated text-based column graph. | |
*/ | |
function asciiGraph(data, minY, maxY, scaleY) { | |
const blocks = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'] // https://en.wikipedia.org/wiki/Block_Elements | |
const rows = new Array(scaleY).fill('') | |
for (const entry of data) { | |
const adjustedValue = (Math.max(Math.min(entry, maxY), minY) - minY) / (maxY - minY) * scaleY | |
const fraction = adjustedValue - Math.floor(adjustedValue) | |
for (let row = 0; row < scaleY; row++) { | |
if (adjustedValue > row) { | |
rows[row] += blocks[blocks.length - 1] | |
} else if (adjustedValue + 1 > row && fraction > 0) { | |
const scaledFraction = Math.floor(fraction * blocks.length) | |
rows[row] += blocks[scaledFraction] | |
} else { | |
rows[row] += ' ' | |
} | |
} | |
} | |
return rows.reverse().join('\n') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment