UNPKG

@exabytellc/utils

Version:

EB react utils to make everything a little easier!

49 lines (46 loc) 1.47 kB
import { handleTryCatch } from "../_helpers/handleError"; import { isDate, isStr } from "../types"; const TIMES = [ ['millisecond', 1000], ['second', 60], ['minute', 60], ['hour', 24], ['day', 7], ['week', 4.34524], ['month', 12], ['year', null] ]; export default function timeSince(date, { minUnit = "millisecond", compareDate = new Date() } = {}) { return handleTryCatch({ n: "timeSince", f: (isDate(date) || isStr(date)) && isStr(minUnit) && (isDate(compareDate) || isStr(compareDate)), e: () => { var time = new Date(compareDate).getTime() - new Date(date).getTime(); // get current level var currentI = 0; var value = Math.abs(time); for (let time of TIMES) { // get and check thresh const threshold = time[1]; if (!threshold) break; // current currentI++; // check value value = value / threshold; if (value > 1) continue; } // retrace var timeSince = []; for (let i = currentI; i >= 0; i--) { const CT = TIMES[i][0]; let int = Math.floor(value); let dec = value - int; if (int > 0) timeSince.push({ name: CT, value: int }); if (minUnit == CT) break; if (i > 0) value = dec * TIMES[i - 1][1]; } // return return { state: Math.sign(time) > 0 ? 'past' : 'future', time: timeSince }; } }); }