Last active
January 21, 2022 17:04
-
-
Save htammen/6cbd147de189b4094004fdbfde6e4ace to your computer and use it in GitHub Desktop.
Calculates weekdays, sundays, saturdays and total days for a time period
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
/* run with 'deno days --help' | |
*/ | |
import containedPeriodicValues from 'https://cdn.skypack.dev/contained-periodic-values'; | |
import sugarDate from 'https://cdn.skypack.dev/sugar-date'; | |
import { ld } from 'https://x.nest.land/[email protected]/mod.ts' | |
import { parse } from "https://deno.land/std/flags/mod.ts" | |
/** | |
* returns a command line argument by name from the args array | |
*/ | |
const getArg = function(argName: string, args: any[]): string { | |
//@ts-ignore | |
const arg = ld.find(args, (arg: string[]) => arg[0] === argName) | |
return arg ? arg[1]: null | |
} | |
/** | |
* Helper method that logs a msg if debug flag is set | |
*/ | |
const logDebug=function(msg: any) { | |
if(bDebug) { | |
console.log(msg) | |
} | |
} | |
// parse the args array into an array of 2-dimensionals array. | |
// Each array element is an array with 2 members: 0-argument, 1-argument value | |
const args = ld.toPairs(parse(Deno.args)) | |
//console.log(args) | |
// save the command line parameters in variables. | |
const bHelp = getArg('help', args) | |
const bDebug = getArg('debug', args) | |
const start = getArg('start', args) || getArg('_', args)[0] || "last month" | |
const end = getArg('end', args) || getArg('_', args)[1] || "today" | |
logDebug(args) | |
class Days { | |
calc(start:any, end:any) { | |
// console.log(start.raw) | |
// console.log(end.raw) | |
let startDay = start.raw.getDay() | |
let days = sugarDate.Date.range(start.raw, end.raw).days() | |
let sundays = containedPeriodicValues(startDay, days + startDay, 0, 7) | |
let saturdays = containedPeriodicValues(startDay, days + startDay, 6, 7) | |
let daysResult = {start: sugarDate.Date.short(start), end: sugarDate.Date.short(end), total: days, sundays: sundays, saturdays: saturdays, weekdays: days-sundays-saturdays} | |
return daysResult | |
} | |
} | |
if(bHelp) { | |
console.log('Usage: days <start end> [options]') | |
console.log(` | |
Options | |
--start: start date. Can be any of sugarjs.com constructor values | |
--end: end date. Can be any of sugarjs.com constructor values | |
--help: show this help screen | |
--debug: show debug information | |
`) | |
Deno.exit(0); | |
} | |
let daysResult = new Days().calc(sugarDate.Date(start).reset(), sugarDate.Date(end)) | |
console.log(JSON.stringify(daysResult)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment