Skip to content

Instantly share code, notes, and snippets.

@noelleleigh
Last active June 28, 2017 21:04
Show Gist options
  • Save noelleleigh/a297de236f58221f092bf9329c1eef5a to your computer and use it in GitHub Desktop.
Save noelleleigh/a297de236f58221f092bf9329c1eef5a to your computer and use it in GitHub Desktop.
Implementation of Alex Yakushev's JavaScript type nightmare (https://twitter.com/unlog1c/status/879421477036183552) feat. a fun pun!
(function undefinedSin() {
// Save the original sine function
const originalSin = Math.sin;
// Encapsulate a scaled sine function
const sinScaled = function sinScaled(value, xScale, yScale) {
return originalSin((value * Math.PI) / xScale) * yScale;
};
// Function that returns a graph formed by the string representation of the input
const sinUndefined = function sinUndefined(input) {
// Sine parameters
const yScale = 2.5;
const xScale = 5;
// Build empty 2D array to hold graph
const graphHeight = 7;
const graphWidth = 22;
const graphYZero = Math.floor(graphHeight / 2);
const graphOrigin = [graphYZero, 0];
const graphArray = Array(graphHeight).fill('').map(() => Array(graphWidth).fill(' '));
// Add y and x-axes using box-drawing characters
graphArray.forEach((horRow => (horRow[0] = '│'))); // eslint-disable-line no-param-reassign
graphArray[graphYZero] = graphArray[graphYZero].map(() => '─');
graphArray[graphOrigin[0]][graphOrigin[1]] = '├';
// Convert input into string representation, repeat until long enough, split to array
const inputString = `${input}`;
const longerInputString = inputString.repeat(Math.ceil(graphWidth / inputString.length));
const inputArray = longerInputString.split('');
// Get the sine values for each input element
const inputSinValues = inputArray.map((_, index) =>
Math.round(sinScaled(index, xScale, yScale)) * -1,
);
// Graph values
inputSinValues.slice(0, graphWidth).forEach((val, index) => {
graphArray[val + graphYZero][index] = inputArray[index];
});
// Join up the graphArray into a string
return graphArray.map(horRow => horRow.join('')).join('\n');
};
// Replace Math.sin
Math.sin = (input) => {
if (input === undefined) {
return sinUndefined(input);
}
return originalSin(input);
};
// Test function
const x = undefined;
return Math.sin(x);
/**
* │
* │ de ef
* │n f d i e
* u────i────n────n────d─
* │ n u e n
* │ ed du
* │
*/
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment