All files index.ts

100% Statements 41/41
100% Branches 22/22
100% Functions 14/14
100% Lines 38/38

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98  10x   7x   2x     2x     2x     2x     2x             8x       7x       21x       9x       26x   10x 1x 9x 1x 8x 2x         9x 17x 2x 2x           7x                     3x 3x 3x 3x       5x 1x 4x 1x 3x 1x 2x 1x   1x           1x   1x  
function stringTime(str: string) {
  const arr = parseAndVerify(str)
 
  const result = {
    get totalSeconds() {
      return arr[0] * 3600 + arr[1] * 60 + arr[2]
    },
    get totalMinutes() {
      return arr[0] * 60 + arr[1] + arr[2] / 60
    },
    get totalHours() {
      return arr[0] + arr[1] / 60 + arr[2] / 3600
    },
    get string() {
      return arrToStr(arr)
    },
    get object() {
      return {
        hour: arr[0],
        minute: arr[1],
        second: arr[2],
      }
    },
    get array() {
      return arr
    },
  }
 
  return result
}
 
function addZero(num: number) {
  return num > 9 ? `${num}` : `0${num}`
}
 
function arrToStr(arr: number[]) {
  return arr.map((a) => addZero(a)).join(':')
}
 
function parseAndVerify(str: string) {
  const arr = str.split(':').map((a) => (a ? +a : 0))
 
  if (arr.length > 3) {
    throw new Error(`Given time ${str} is invalid`)
  } else if (arr.length === 2) {
    arr.push(0)
  } else if (arr.length === 1) {
    arr.push(0, 0)
  } else {
    // noop
  }
 
  for (let i = 1; i <= 2; i++) {
    if (arr[i] > 60) {
      const k = i === 1 ? 'Minute' : 'Second'
      throw new Error(
        `Given time ${str} is invalid. ${k} can't be greater than 60`
      )
    }
  }
 
  return arr
}
 
type Time =
  | number[]
  | { hour: number; minute: number; second: number }
  | { seconds: number }
  | { minutes: number }
  | { hours: number }
 
function secondsToString(seconds: number) {
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = Math.floor((seconds % 3600) % 60)
  return `${addZero(h)}:${addZero(m)}:${addZero(s)}`
}
 
function reverse(time: Time) {
  if (Array.isArray(time)) {
    return arrToStr(time)
  } else if ('seconds' in time) {
    return secondsToString(time.seconds)
  } else if ('minutes' in time) {
    return secondsToString(time.minutes * 60)
  } else if ('hours' in time) {
    return secondsToString(time.hours * 3600)
  } else {
    return `${addZero(time.hour)}:${addZero(time.minute)}:${addZero(
      time.second
    )}`
  }
}
 
stringTime.reverse = reverse
 
export = stringTime