UNPKG

date-limits

Version:

Check if a date is before a flexible limit.

48 lines (47 loc) 1.53 kB
export function* makeYearGenerator(config = undefined, startFrom, lowerLimit = 1970) { if (config === undefined) { let currentNum = startFrom; while (currentNum >= lowerLimit) { yield currentNum--; } return null; } if (typeof config === 'number') { if (config <= startFrom) { yield config; } return null; } if (Array.isArray(config)) { for (let i = config.length; i >= 0; i--) { if (config[i] > startFrom) continue; yield config[i]; } return null; } if ('slope' in config) { const { slope: a, offset: b = 0 } = config; const x = Math.floor((startFrom - b) / a); let currentNum = a * x + b; while (currentNum >= lowerLimit) { yield currentNum; currentNum -= a; } return null; } config.from ?? (config.from = lowerLimit); config.to ?? (config.to = startFrom); if (config.from > startFrom) { return null; } if (config.from > config.to) { throw new Error(`Config range cannot contain "from" value higher than "to" value, got ${config.from} and ${config.to} respectively.`); } let currentNum = startFrom > config.to ? config.to : startFrom; // if config.from > startFrom then the loop will never run while (currentNum >= config.from) { yield currentNum--; } return null; }