Created
April 8, 2023 20:30
-
-
Save ihatecsv/0047fad33751dffce00b7cab5a5e6778 to your computer and use it in GitHub Desktop.
generateAsciiGraph by GPT4
This file contains hidden or 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
// Written by GPT4 | |
// Prompt: | |
// Write a JS function that returns a string of an ASCII graph for a given function string. | |
// The function string should be the text of an anonymous JS function that returns a single number. | |
// Use eval to figure out the result of the func. | |
function generateAsciiGraph(funcStr, width = 50, height = 10, minX = -10, maxX = 10, minY = -10, maxY = 10) { | |
const func = eval(funcStr); | |
const stepX = (maxX - minX) / width; | |
const stepY = (maxY - minY) / height; | |
function getY(x) { | |
return func(x); | |
} | |
function getX(index) { | |
return minX + index * stepX; | |
} | |
function scaleToAxis(val, axisSize, min, max) { | |
return Math.floor(((val - min) / (max - min)) * axisSize); | |
} | |
let graph = ''; | |
for (let j = height - 1; j >= 0; j--) { | |
for (let i = 0; i < width; i++) { | |
const x = getX(i); | |
const y = getY(x); | |
const scaledY = scaleToAxis(y, height, minY, maxY); | |
const scaledX = scaleToAxis(x, width, minX, maxX); | |
if (scaledY === j) { | |
graph += '*'; | |
} else if (scaledX === i && scaledY === 0) { | |
graph += '+'; | |
} else if (scaledX === i) { | |
graph += '-'; | |
} else if (scaledY === 0) { | |
graph += '|'; | |
} else { | |
graph += ' '; | |
} | |
} | |
graph += '\n'; | |
} | |
return graph; | |
} | |
const funcStr = "(x) => Math.sin(x)"; | |
console.log(generateAsciiGraph(funcStr)); |
Author
ihatecsv
commented
Apr 8, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment