Skip to content

Instantly share code, notes, and snippets.

@tgmarinho
Created August 22, 2022 13:47
Show Gist options
  • Save tgmarinho/b95d98d81172bf46bd64216e1feef54b to your computer and use it in GitHub Desktop.
Save tgmarinho/b95d98d81172bf46bd64216e1feef54b to your computer and use it in GitHub Desktop.
Se usar IIFE você consegue ter a inferência funcionando
import { DateTime, DurationLikeObject } from 'luxon'
const DAYS_IN_SECONDS = 86400
const HOURS_IN_SECONDS = 3600
const MINUTES_IN_SECONDS = 60
/*
const getUnit = (challengePeriod: number): keyof DurationLikeObject => {
let unit: keyof DurationLikeObject = 'days'
if (challengePeriod >= DAYS_IN_SECONDS) {
unit = 'days'
} else if (challengePeriod >= HOURS_IN_SECONDS) {
unit = 'hours'
} else if (challengePeriod >= MINUTES_IN_SECONDS) {
unit = 'minutes'
} else {
unit = 'seconds'
}
return unit
}
*/
export const displayChallengePeriod = (challengePeriod: number): string => {
if (challengePeriod <= 0) {
return '-'
}
const format = (() => {
if (challengePeriod >= DAYS_IN_SECONDS) {
return 'days'
} else if (challengePeriod >= HOURS_IN_SECONDS) {
return 'hours'
} else if (challengePeriod >= MINUTES_IN_SECONDS) {
return 'minutes'
}
return 'seconds'
})()
const now = DateTime.now()
const period = now.plus({ seconds: challengePeriod })
return period.diff(now, [format]).toHuman()
}
@tgmarinho
Copy link
Author

const getUnit = (challengePeriod: number) => {
  if (challengePeriod >= DAYS_IN_SECONDS) {
    return 'days'
  } else if (challengePeriod >= HOURS_IN_SECONDS) {
    return 'hours'
  } else if (challengePeriod >= MINUTES_IN_SECONDS) {
    return 'minutes'
  }
  return 'seconds'
}


period.diff(now, [getUnit(challengePeriod)]).toHuman()


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment