Skip to content

Instantly share code, notes, and snippets.

@noelleleigh
Last active March 17, 2018 19:55
Show Gist options
  • Save noelleleigh/9242b636766e17ddb647820d0764ac51 to your computer and use it in GitHub Desktop.
Save noelleleigh/9242b636766e17ddb647820d0764ac51 to your computer and use it in GitHub Desktop.
Parameterized Javascript implementation of https://twitter.com/slimedaughter/status/927729872092270592 just for the hell of it.
/**
* Return an array of objects representing a triangle wave, with a values and direction for each point.
* @param {Number} length - The desired length of the array.
* @param {Number} height - The desired peak value for the wave.
* @returns {Object[]} - Array of objects like `{wiggle: <Number>, wiggle_down: <Boolean>}`.
*/
function makeWiggle(length, height) {
const output = []
let wiggle = 0;
let wiggle_down = false;
output.push({wiggle: wiggle, wiggle_down: wiggle_down});
for (let i = 0; i < length - 1; i++){
if (wiggle < height && !wiggle_down) {
wiggle += 1;
} else if (wiggle >= height && !wiggle_down) {
wiggle_down = true;
} else if (wiggle > 0 && wiggle_down) {
wiggle -= 1;
} else if (wiggle <= 0) {
wiggle_down = false;
}
output.push({wiggle: wiggle, wiggle_down: wiggle_down});
}
return output
}
/**
* Return a 2D array of strings representing the wiggle defined in `wigglesArray`.
* @param {array} wigglesArray - Output from `makeWiggle()`.
* @param {int} height - The max wiggle value from `wigglesArray`
* @returns {Array.<string[]>}
*/
function prepareWigglesOuput(wigglesArray, height) {
const graphHeight = height + 1;
const pixelMap = Array(graphHeight).fill(undefined).map(() => Array(wigglesArray.length).fill('·'));
for (let i = 0; i < wigglesArray.length; i ++) {
pixelMap[-1 * (wigglesArray[i].wiggle) + graphHeight - 1][i] = `${wigglesArray[i].wiggle_down ? '↓' : '↑'}`;
}
return pixelMap
}
/**
* Return a string-rendering of a triangle wave.
* @example
* renderWiggles(10, 3)
* // · · · ↑ ↓ · · · · ·
* // · · ↑ · · ↓ · · · ·
* // · ↑ · · · · ↓ · · ↑
* // ↑ · · · · · · ↓ ↑ ·
* @param {Number} length - The desired length of the wave.
* @param {Number} height - The desired peak value for the wave.
* @returns {String}
*/
function renderWiggles(length, height) {
const wiggles = makeWiggle(length, height);
const pixels = prepareWigglesOuput(wiggles, height);
return pixels.map(row => row.join(' ')).join('\n');
}
console.log(renderWiggles(40, 6));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment