I'm trying to create a program that will try to build a target string character by character by generating random characters. I have come up with the following Nodejs program with a little bit of Google help:
const args = process.argv.slice(2)
const targetWord = args[0]
let builtWord = ''
function getRandomChar() {
return String.fromCharCode(Math.floor(Math.random() * (126 - 32 + 1)) + 32)
}
function updateWord() {
const {length} = builtWord
const nextChar = getRandomChar()
process.stdout.write('\r')
process.stdout.write(builtWord)
process.stdout.write(nextChar)
if (targetWord[length] === nextChar) {
builtWord += nextChar
}
}
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
async function main() {
while (true) {
updateWord()
if (builtWord === targetWord) {
break
}
await sleep(1000 / 16)
}
}
main()
What are your thoughts on it, anything I can improve or do differently? Thanks 😙!