Using a split string to destructure an array with a mix of let and const variables

There is a problem with TS:

An error occurs stating that 'parsedHours' and 'parsedMinutes' should be declared as constants by using 'const' instead of 'prefer-const'.

This issue arises when attempting to destructure an array after performing a string split operation:

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

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

Hours and minutes are recommended to be declared as constants, but seconds and millis can change so they should remain as let variables. There are several ways to address this issue, but finding an elegant solution has been challenging.

Any suggestions?

Answer №1

To split a String using RegExp and String.split(), you can split by the characters [.:]:

const separateTime = (str) => {
  const [
    hour = '00',
    minute = '00',
    second = '00',
    millisecond = '000'
  ] = str.split(/[.:]/);

  console.log({
    hour,
    minute,
    second,
    millisecond
  });
}

separateTime("12:34:56")

separateTime("12:34:56.35")

Answer №2

If the only reason Seconds and Millis might vary is due to that specific if statement, then there may be a flaw in your initial approach. This is because after the initial split, parsedSeconds does not solely represent "parsed seconds", but rather "parsed seconds with an optional decimal part".

Instead of relying on assumptions, try parsing the actual format using regex:

const [
  , // discard "full match"
  parsedHours,
  parsedMinutes,
  parsedSeconds,
  parsedMillis = "000"
] = "12:34:56".match(/^(\d{2}):(\d{2}):(\d{2})(?:\.(\d{3}))?$/) || [];

In this context, all the parsed components remain constant.

Take note of the final || [], which accounts for cases where the input doesn't follow the expected format. You could name the full match as parsedResult and verify with

if( !parsedResult) throw 'something';

Answer №3

When faced with this issue, you have a variety of choices:

  1. You can disable the lint rule (more than likely coming from TSLint or ESLint rather than TypeScript itself).

  2. Save the array and then utilize either const or let based on your preference.

  3. Utilize a regular expression to use const for all values, possibly employing named capture groups to accommodate different input formats.

For option #2, consider the following code snippet:

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

And for option #3, here is an example:

const rexTime = /^(?<hours>\d{1,2}):(?<minutes>\d{1,2}):(?<seconds>\d{1,2})(?:\.(?<millis>\d{1,3}))?$/;
function example(timeString) {
    const {
        groups: {
            hours = "00",
            minutes = "00",
            seconds = "00",
            millis = "000"
        } = {}
    } = rexTime.exec(timeString) ?? {};
    console.log(
        timeString,
        "=>",
        hours,
        minutes,
        seconds,
        millis
    );
}

example("12:34:56");
example("12:34:56.123");

There are numerous approaches to tackle this problem, and the above examples just scratch the surface.

Answer №4

Is it possible to replace the . with a : and then split everything apart? (Alternatively, if you prefer not to do that, the second example excludes the dot replacement)

By the way, you can simply spread the remaining content as constants, and then work on the subparts:

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

   console.log(rest);

const [
  parsedHours2 = '00',
  parsedMinutes2 = '00',
  ...rest2
] = "12:34:56.123".split(':');
let [
  parsedSeconds2 = '00',
  parsedMillis2 = '000'
] = rest2;  

console.log(rest2);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Local storage synchronization in progress, please hold on

Currently, there seems to be a synchronization issue between the local storage and the server. Countries, cities, and users are synchronized with the server separately through different Ajax calls. The problem at hand is that other JavaScript codes (such ...

Please ensure that all files have finished downloading before proceeding to create the object

Within my Session class, I've been instantiating objects from my Question Class. Within this process, images are being downloaded to a local path. However, the issue arises when my LaTeXDoc class demands that all images are already saved at the time o ...

Tips for integrating the react-financial-charts library into your React and JavaScript project

While exploring the react-financial-charts library, I discovered that it is written in TypeScript (TS). Despite my lack of expertise in TypeScript, I am interested in using this library in my React+JS project due to its active contributions. However, I hav ...

TypeError: "Table" has not been declared

This is my first experience with the script editor. I have been given the task of creating a pivot table for Google Sheets using a script. // This script creates a pivot table in Google Sheets function createPivotTable() { var ss = SpreadsheetApp.getAc ...

Changing the designated materialUI class

Within the project, I am utilizing this theme: export const theme = createMuiTheme({ ...defaultThemeConfig, overrides: { ...defaultThemeConfig.overrides, MuiListItem: { root: { '&:nth-child(odd)': { backgro ...

Encountering the "TypeError: Unable to access property 'indexOf' of undefined" error while utilizing the ipfs-api

During my development work with the ipfs-api, I ran into an issue where adding an image file to the ipfs node was not functioning properly. Upon further investigation into the error details, it appears that the protocol is being treated as undefined in the ...

Having trouble utilizing yarn to import Mapbox into TypeScript

My process involves using the command: yarn add --dev @types/mapbox-gl @types/geojson This successfully adds mapbox and geojson to my project. I can see them when attempting to import mapboxgl. Next, I create something similar to this: import * as L ...

Slick Slider fails to load on web browsers

Hi everyone, I have a snippet of HTML code that I need help with: <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css"/> </head> <body> ...

Why is there a presence of quotation marks in the value stored in my local storage?

I have been attempting to extract data from a MySQL database using the following code: app.get("/api/getStudentsFromClass", async(req,res) => { const currentClassClicked = req.query.currentClassClicked connection.query( " ...

NestJS integration tests are failing due to an undefined Custom TypeORM Repository

I am currently facing a challenge while writing integration tests for my Nest.js application. The custom TypeORM repositories in my test context are being marked as undefined. This issue may be occurring because I am not utilizing @InjectRepository. Instea ...

The standard category of class method parameter nature

I'm encountering difficulties when attempting to correctly define a method within a class. To begin with, here is the initial class structure: export class Plugin { configure(config: AppConfig) {} beforeLaunch(config: AppConfig) {} afterSe ...

Angular binding causing decimal inaccuracies

Within my $scope, I have a variable tobing that can be either 2.00 or 2.20, and I am binding it to: <span>{{datasource.tobind}}</span> I want the displayed text to always show "2.00" or "2.20" with the two last digits, but Angular seems to au ...

What is the best way to eliminate blank values ("") from an array?

I am working with a two-dimensional array that was generated from an HTML table using jQuery, but I have noticed that some values are empty and are displaying as "". How can I go about removing these empty values from the array? <table> ...

How can I extract particular combinations from a PHP array?

I have a unique question that is quite specific and despite searching online, I couldn't find an answer. So, I decided to seek advice here. Imagine my webpage has three sliders: one for selecting color options for a square, another for a circle, and ...

Begin a SeleniumWebDriver session after Google Chrome has been launched beforehand

I am looking to create an automation using SeleniumWebDriver and Node.js, but I am facing an issue where I cannot start the automation if Google Chrome is already open and in use by the user. Currently, my workaround is to close all instances of Chrome be ...

Instructions on transforming an img into an Image component within next.js

I have successfully implemented all the logic in this component, tailored to the <img> tag. Now, I am aiming to apply the same logic to the Image component. However, when attempting to do so, I encounter an error. TypeError: Failed to construct &apos ...

Creating a TypeScript library with Webpack without bundling may seem like a daunting task, but

Currently, I am developing a React component package using Typescript and NPM. During my research, I discovered that generating individual .js and .d.ts files is more beneficial than bundling them into one bundle.js file. However, I am facing difficulty in ...

A TypeScript class utilizing a static variable with the singleton design pattern

I have a query regarding the most effective way to code this scenario: Within a class, I require a static variable that is accessible throughout the entire project: connection Singleton without namespace: class Broker { static connection: Connection = u ...

Executing a function after a subscriber has finished in Angular 8+

Welcome fellow learners! Currently, I am diving into the world of Angular and Firebase. I am facing an interesting challenge where I fetch ticket data from my collection and need to add new properties to it. However, the issue arises when my ordering funct ...

Resetting an object back to its initial value while preserving its bindings in AngularJS

My service deals with a complex object retrieved from an API, like this: { name: "Foo", addr: { street: "123 Acacia Ave", zip: "10010" } } The initial value is stored in myService.address, and another variable holds a copy of ...