Skip to content

Instantly share code, notes, and snippets.

@CoderPrans
Created February 19, 2024 08:21
Show Gist options
  • Save CoderPrans/585c99815f2b908165a531a5249f083f to your computer and use it in GitHub Desktop.
Save CoderPrans/585c99815f2b908165a531a5249f083f to your computer and use it in GitHub Desktop.
a sample application of generator functions to iterate indefinitely yet yield a definite result.
// import astronomy-engine
let astronomy = require('astronomy-engine');
let tithis = [ "Shukl Prti. (Br 1)", "Shukl Dwit. (Br 2)", "Shukl Trit. (Br 3)", "Shukl Catu. (Br 4)", "Shukl Panch. (Br 5)", "Shukl Sast. (Br 6)", "Shukl Sapt. (Br 7)", "Shukl Asht. (Br 8)", "Shukl Nava. (Br 9)", "Shukl Dasm. (Br 10)", "Shukl Ekad. (Br 11)", "Shukl Dwad. (Br 12)", "Shukl Tryod. (Br 13)", "Shukl Caturd. (Br 14)",
"Purnima (Full Moon)",
"Krshn Prti. (Da 1)", "Krshn Dwit. (Da 2)", "Krshn Trit. (Da 3)", "Krshn Catu. (Da 4)", "Krshn Panch. (Da 5)", "Krshn Sast. (Da 6)", "Krshn Sapt. (Da 7)", "Krshn Asht. (Da 8)", "Krshn Nava. (Da 9)", "Krshn Dasm. (Da 10)", "Krshn Ekad. (Da 11)", "Krshn Dwad. (Da 12)", "Krshn Tryod. (Da 13)", "Krshn Caturd. (Da 14)",
"Amavasya (New Moon)"];
function getTithi(date) {
let moonFactor = astronomy.MoonPhase(date) / 12;
let tithiIndex = Math.floor(moonFactor);
let tithiRemaining = moonFactor % 1;
return [tithis[tithiIndex], parseFloat(tithiRemaining*100).toFixed(2) + "%"];
}
// generator function*
function* tithiTransitions() {
let time = new Date().getTime();
let interval = 10*1000;
let i = 1;
let tithi = getTithi(new Date());
while(true){
let nextTithi = getTithi(new Date(time + i*interval));
// continue iterating, yield at a tithi transition.
if(nextTithi[0] !== tithi[0]) {
yield [nextTithi[0], new Date(time + i*interval).toString()];
tithi = nextTithi;
}
i+=1;
}
}
// yields once then stops until called '.next()' again.
let tithiterator = tithiTransitions();
// get tithi transition times for next 30 tithis.
for(let i=0; i<30; i++) {
console.log(tithiterator.next().value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment