Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@skava/utils / src / getActualDate.ts
Size: Mime:
type Months =
  | 'January'
  | 'February'
  | 'March'
  | 'April'
  | 'May'
  | 'June'
  | 'July'
  | 'August'
  | 'September'
  | 'October'
  | 'November'
  | 'December'

const months = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December',
]

/**
 * @todo why are we mixing the strings and numbers?
 */
export interface SeparatedDate {
  year: string
  month: string | number
  date: string
}

const seperateDate = (x: string): SeparatedDate => {
  // @todo @fixme @@perf
  x = x || ''

  const dateSplitter =
    x && x.includes('/') ? '/' : x && x.includes('-') ? '-' : ''

  const dateSplit = x.split(dateSplitter)
  const year = dateSplit[0]
  const month = parseInt(dateSplit[1], 10) || 0
  const matchedDate = dateSplit[2] || ''

  const date = matchedDate.includes(' ')
    ? matchedDate.split(' ').shift() || ''
    : matchedDate

  const dateObj = {
    year,
    month,
    date,
  }
  return dateObj
}

export type DateFormat = 'yyyy' | 'mmm' | 'dd' | 'yy' | string

/**
 * @note this was unsafe previously, now it is safe with typescript
 */
function getActualDate(actualDate: string, dateFormat: DateFormat) {
  const { year, month, date } = seperateDate(actualDate)
  const monthName = months[month] as Months
  if (dateFormat.includes('yyyy')) {
    dateFormat = dateFormat.replace('yyyy', year)
  }
  if (dateFormat.includes('mmm')) {
    dateFormat = dateFormat.replace('mmm', monthName.substring(0, 3))
  }
  if (dateFormat.includes('dd')) {
    dateFormat = dateFormat.replace('dd', date)
  }
  return dateFormat
}

export { getActualDate }
export default getActualDate