Skip to content
Advertisement

Mixed let/const array destructuring from split string

TS throws an error:

'parsedHours' is never reassigned. Use 'const' instead    prefer-const
'parsedMinutes' is never reassigned. Use 'const' instead  prefer-const

When trying to deconstruct this array, after a string split:

let [
  parsedHours = '00',
  parsedMinutes = '00',
  parsedSeconds = '00',
  parsedMillis = '000'
] = "12:34:56".split(':');

if (parsedSeconds.includes('.')) {
  [parsedSeconds, parsedMillis] = parsedSeconds.split('.');
}

Hours and minutes should be declared as constants, but Seconds and Millis may change, thus should be declared as let. This can be fixed in many approaches, but I can’t find a beautiful way of doing this.

Any ideas?

Advertisement

Answer

You can use String.split() with a RegExp to split by [.:]:

const splitTime = (str) => {
  const [
    parsedHours = '00',
    parsedMinutes = '00',
    parsedSeconds = '00',
    parsedMillis = '000'
  ] = str.split(/[.:]/);

  console.log({
    parsedHours,
    parsedMinutes,
    parsedSeconds,
    parsedMillis
  });
}

splitTime("12:34:56")

splitTime("12:34:56.35")
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement