@binaryme/suncalc-callback
TypeScript icon, indicating that this package has built-in type declarations

1.2.1 • Public • Published

A callback/promise approach to SunCalc. SunCalc provides Date values for a specific date and geolocation.

The getTimes function is passed as a parameter where needed to make it possible to isolate different instances of the SunCalc library.

This library assists with a more procedural approaches.

Usage

Setup a callback function to be called as sunlight events occur:

import { getTimes } from 'suncalc';

onTimes(35.2029, -111.66485, getTimes, name => {
  console.log(`It is now ${name}`);
})

There is also a Promise based function.

import { getTimes } from 'suncalc';

while (true) {
  const [name] = await nextTime(35.2029, -111.66485, getTimes);
  console.log(`It is now ${name}`);
}

If you need the callback to be called 5 minutes prior to every sunlight event an optional parameter can be used.

onTimes(lat, lon, getTimes, (name, date) => {
  console.log(`${name} in 5 min. The time will then be ${date}`);
}, 1000 * 60 * 5)

Same for the promise.

while (true) {
  const [name, date] = await nextTime(lat, lon, getTimes, 1000 * 60 * 5);
  console.log(`${name} in 5 min. The time will then be ${date}`);
}

To get the next and previous sunlight events use getPrevNext.

const { prev, next } = getPrevNext(new Date(), lat, lon, getTimes);
const [prevName, prevDate] = prev;
const [nextName, nextDate] = next;
console.log(`${prevName} was at ${prevDate.toTimeString()}`);
console.log(`${nextName} will be at ${nextDate.toTimeString()}`);

To filter the sunlight events of getPrevNext an optional parameter may be used.

const { prev, next } = getPrevNext(new Date(), lat, lon, getTimes, ['solarNoon']);
const [prevName, prevDate] = prev;
const [nextName, nextDate] = next;
console.log(`Pervious solar noon was at ${prevDate.toTimeString()}`);
console.log(`Next solar noon will be at ${nextDate.toTimeString()}`);

If you are a fan of rxjs an Observable can easily be made.

const $ = new Observable<[TimeName, Date]>(subscriber => {
  const cancel = onTimes(lat, lon, getTimes, (name,date) => subscriber.next([name,date]), msInAdvance);
  return () => cancel();
});
$.subscriber(([name,date]) => {
  console.log(`It is now ${name}`);
})

Dependencies (0)

    Dev Dependencies (9)

    Package Sidebar

    Install

    npm i @binaryme/suncalc-callback

    Weekly Downloads

    2

    Version

    1.2.1

    License

    MIT

    Unpacked Size

    11.3 kB

    Total Files

    5

    Last publish

    Collaborators

    • gwest7