What is the reason for the exclusion of square brackets in the reduce()

My current code:

var isValid = function(s) {
    let arr = [...s];

    arr.reduce((acc, cur) => {
        console.log(`arr in reduce: ${arr}`);
        console.log(`acc: ${acc}`);
        console.log(`cur: ${cur}`);
        if ((acc && cur)
        && (
            (acc === '(' && cur === ')')
            || (acc === '{' && cur === '}')
            || (acc === '[' && cur === ']')
        )) {
            arr.splice(arr.indexOf(acc), 2);
            console.log(`arr after splice: ${arr}`);
            return arr;
        }
        else {
            console.log(`else statement: ${cur}`);
            return cur;
        }
    });

    return arr.length === 0 ? true : false;
};

console.log(isValid("()[]{}"));

Requirements for the code to return true:

  • Open brackets must be closed by the corresponding type of brackets.
  • Open brackets must be closed in the correct sequence.

Issue with my code when tested with "()[]{}": it consistently returns [,], and I am unsure why. I have attempted regex and ASCII conversions for square brackets without success.

Answer №1

To determine the validity of a string containing opening and closing characters, create a stack to store expected closing characters when encountering open characters.

If an open character is found, push the corresponding closing character to the stack. Otherwise, compare the popped value from the stack with the current character.

var isValidString = function([...chars]) {
        var stack = [],
            openPairs =  { '(': ')', '[': ']', '{': '}' };
        return chars.every(char => char in openPairs ? stack.push(openPairs[char]) : char === stack.pop())
            && !stack.length;
    };

console.log(isValidString("()[]{}"));
console.log(isValidString("(({}[()]))[]{}"));
console.log(isValidString("()[]{}}"));
console.log(isValidString("["));

Answer №2

After performing the splice operation, it is important to note that the length of the array changes. Consequently, when checking the logs, you will observe that [,] is being skipped in the tests due to this modification (the index values in the reduce steps no longer correspond to the array elements). To address this issue, it is advisable to work with a copy of the original array rather than manipulating the array directly during splicing operations.

Furthermore, it should be noted that the current code implementation may not handle nested parenthesis or brackets correctly. Also, caution must be exercised while using indexOf to locate the value of cur, as it returns the index of the first occurrence which may lead to discrepancies if the code logic is altered.

var isValid = function(s) {
    let arr = [...s], copy = [...s];

    arr.reduce((acc, cur) => {
        console.log(`arr in reduce: ${arr}`);
        console.log(`copy in reduce: ${copy}`);
        console.log(`acc: ${acc}`);
        console.log(`cur: ${cur}`);
        if ((acc && cur)
            && (
                (acc === '(' && cur === ')')
                || (acc === '{' && cur === '}')
                || (acc === '[' && cur === ']')
            )) {
            copy.splice(copy.indexOf(acc), 2);
            console.log(`copy after splice: ${copy}`);
            
            return arr;
        }
        else {
            console.log(`else statement: ${cur}`);
            return cur;
        }
    });

    return copy.length === 0 ? true : false;
};

console.log(isValid("()[]{}"));

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

Unveiling the Mystery: Uncovering the Selected Item in Ionic Checkboxes

I am trying to implement a feature in Ionic checkboxes where I can get the selected item when a user checks one or more checkboxes. Specifically, I want to identify which books the user has selected. Below are snippets of my code: <ion-item ng ...

Unable to utilize query parameters with an ExpressJS API on localhost

Within my index.js file app.use('/api/v1/users', userRouter) In the Router file router.get("/:id", getUserDataById); When using Postman: The GET URL I am using is: http://localhost:3000/api/v1/users?id=120622 The error message is: C ...

When I navigate using state.go in my controller, the Ionic slide menu fails to appear

Hello everyone, I am currently using Ionic to develop my application and have implemented a slide menu. However, I encountered an issue where the slide menu fails to work when changing views using "$state.go". How can I resolve this? The Router : "use st ...

Pseudo code example for fetching data from MySQL using PHP associative arrays

I am faced with the task of retrieving data from two MySQL tables - products and prodGroups. The desired outcome is to have this information structured in the form of an associative array like so: Array ( [0] => Product Group 1 =& ...

Comparing the outcomes of using a custom memset function with char *s = "Hello" versus char s[] = "Hello". Can you explain why one method does not actually set memory but still prints the array?

I'm seeking clarification on the distinction between declaring and initializing a pointer to an array of characters like char *s = "Hello"; versus the more common method of using char s[] = "Hello";. I attempted to use my recreated memset function on ...

Incorporate a 'back' button in the tab content of vue-form-wizard

Currently, I'm working on implementing a vue form wizard from the repository: https://github.com/BinarCode/vue-form-wizard My challenge is to include a button in the second tab-content itself instead of having it placed in the footer. I attempted th ...

Substitute phrases with hyperlinks using JavaScript (or Ruby)

After researching numerous resources on SO, I have managed to come up with a solution that is very close to working. My goal is to replace words/phrases within a <p> tag with links using jQuery after the page has loaded (although I am open to a Ruby ...

Creating a Gulpfile.js that efficiently manages a multitude of files spread across various folders

For my ongoing WordPress projects, I am simultaneously working on themes and plugins. In my theme folder, I have a gulpfile.js that compiles .scss files into .css. I am considering creating a central "master" gulpfile in the root folder to compile .scss fi ...

Combining GET and POST requests in ExpressJS on a single route

As I work on setting up a questionnaire in Express JS with EJS as the renderer, I have already created individual pages for each question. These pages are accessible through static links using the app.get('/question/:number?', routes.questions) f ...

Calculating the height of a window using JavaScript and Ajax

As you navigate down the page, new images start loading at the bottom. However, I want them to load before reaching the very end of the page. Below is the code snippet from the page template: <?php /** * Template Name: gallery */ get_header(); ?> ...

Ways to incorporate the point count divided by a specified value onto a map

I am working with Mapbox GL JS and I have a specific requirement to display the number of markers in a cluster divided by 10 on the map. To achieve this, I am utilizing the point_count and point_count_abbreviated attributes in the code snippet below: map ...

What technique can be used to shift focus to the following text field after clicking a button

HTML : <input type="text" class="mytextbox"> <input type="text" class="mytextbox"> <input type="text" class="mytextbox"> <input type="text" class="mytextbox"> <input type="button" class="mybutton" value="focus next" onclick="f ...

Setting a minimum width for an inline element that is not displayed as inline-block

Is there a way to set the min-width on a contenteditable div while keeping other elements inline with it? I have looked at solutions that use inline-block, but I am unable to use this behavior. When inline-block wraps, it still acts like a block element, ...

Securely authenticate with Node.js using screen scraping techniques

Attempting to scrape a website with authentication in node.js, but encountering an issue when trying to submit the form: "Your browser "for others" does not support our site." The username is being set, but the password field appears to be empty. Curren ...

sophisticated HTML navigation bar

I am looking for a way to create a menu where the drop-down items overlay the rest of the menu when the screen width is small. Here is my current code: nav{ line-height:100%; opacity:.9; }nav ul{ background: #999; padding: 0px; border-radius: 20px; ...

Is there a way to perform unit testing on JavaScript code that runs following the completion of a CSS transitionEnd event

I am working with a bootstrap modal window and using qunit+sinonjs (fake timers). However, I have noticed that one element (div class='modal-backdor') remains on the page despite my efforts. You can view the issue here: http://jsfiddle.net/valu ...

Delivery person receiving biscuit but my internet browser doesn't seem to be getting it when I attempt to retrieve it

Currently, I am in the process of creating a website using Flask and React. The user is required to input an email and password on a form, which is then sent via axios.post to the backend. The backend checks if the email and password match with the databas ...

What is the best way to parse a text file based on a specific delimiter and then store each element of the resulting array

I have been working on creating a login page, where I am trying to import the user's data into an array. The goal is to match the entered username and password with the ones stored in the array. Can someone please assist me with this? Text File: 72| ...

What is the best way to display a dynamic JSON array in an HTML table?

I have a function that is triggered by a button press and updates an array order: var order = []; function updateCart(item) { var index = order.findIndex(i => i.id == item.id); if (index != -1) { order.splice(index, 1); order.p ...

What are some ways that we can enhance each other's value?

I am currently delving into the realm of Java-script, with the goal of creating an input field for numbers. My vision is to have a scenario where when a user enters a number in the input field, my script will display it in a paragraph or another text field ...