Created
January 3, 2025 23:28
-
-
Save beatak/4e4b0e196bfdde96c543bff9e9772326 to your computer and use it in GitHub Desktop.
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
'use strict'; | |
const Readline = require('node:readline'); | |
const RL = Readline.createInterface({ | |
input: process.stdin, | |
output: process.stdout, | |
}); | |
const main = async function () { | |
const year = await runReadline('What year were you born in? ', checkerInt); | |
const month = await runReadline('What month were you born on? ', checkerInt); | |
const day = await runReadline('What day of the month were you born on? ', checkerInt); | |
const offset = await runReadline('What timezone were you born in? Please type in offset. eg. Japan 9, SF -8 ', checkerInt); | |
const [sign, zeroPadHours] = destructureOffset(offset); | |
const bday = new Date(`${year}-${month}-${day}T12:00:00.000${sign ? '+' : '-'}${zeroPadHours}:00`); | |
console.log(`You are ${getWeek(bday)} weeks old`); | |
process.exit(0); | |
}; | |
const getWeek = function (date) { | |
return Math.floor( (Date.now() - date.valueOf()) / (60 * 60 * 24 * 7 * 1000)) | |
}; | |
const destructureOffset = function (num) { | |
const abs = Math.abs(num); | |
const zeroPad = `0${abs}`.slice(-2); | |
return num > 0 ? [true, zeroPad] : [false, zeroPad]; | |
}; | |
const checkerInt = function (str) { | |
const result = parseInt(str, 10); | |
if (isNaN(result)) { | |
return null; | |
} | |
return result; | |
} | |
const runReadline = async function (question, checker) { | |
let count = 0; | |
let result; | |
loop:while (true) { | |
const answer = checker(await runReadlineImpl(question)); | |
if (answer !== null) { | |
result = answer; | |
break loop; | |
} else { | |
++count; | |
if (count > 5) { | |
console.log('Too many invalid inputs. Exiting.'); | |
process.exit(1); | |
} | |
console.log('Invalid input. Please try again.'); | |
} | |
} | |
return result; | |
}; | |
const runReadlineImpl = function (question) { | |
return new Promise((resolve, reject) => { | |
try { | |
RL.question(question, (answer) => { | |
resolve(answer); | |
}); | |
} catch (err) { | |
reject(err); | |
} | |
}); | |
}; | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment