Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How to write a javascript function that checks if first and last characters in a string are equal

I been doing this javascript challenge and I'm pretty close, but something is off.Here's the challenge:

Given an array of strings containing three types of braces: round (), square [] and curly {} Your task is to write a function that checks whether the braces in each string are correctly matched. Prints 1 to standard output (console.log) if the braces in each string are matched and 0 if they're not (one result per line)

my code is this:

var infoToParse = [ ")(){}", "[]({})", "([])", "{()[]}", "([)]" ]; 

function checkBraces(infoToParse) {
    var tabChars = infoToParse;
    for (i= 0; tabChars.length - 1; i+=1) {
        if (tabChars[i].charAt(0) === tabChars[i].charAt(tabChars[i].length-1)){
            console.log(1);
        }else{
            console.log(0);
        }
    }
}

checkBraces(infoToParse);

The output with the current array items should be Output: 0 1 1 1 0

1 Answer

your code is testing whether the first and last character in the string are the same. In all cases they are not [ ")}", "[)", "()", "{}", "(]"] so your code is actually working correctly. It's just not solving the problem that you are trying to solve.

to get yours to work I made a few modifications. This makes sure the first and last characters match. It does NOT make sure that all pairs are "correctly matched"

<!DOCTYPE html>
<html>
<head>
    <title>Object</title>
</head>
<body>

    <script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script>
    <script>

        //added 1 item to the end that will pass
        var infoToParse = [ ")(){}", "[]({})", "([])", "{()[]}", "([)]", "{(){" ]; 

        function checkBraces(infoToParse) {
            var tabChars = infoToParse;

            //fixed your condition
            //for (i= 0; tabChars.length - 1; i+=1) {
            for (var i= 0; i<tabChars.length; i+=1) {

                //change the log to display "item x is 1 or 0"
                if (tabChars[i].charAt(0) === tabChars[i].charAt(tabChars[i].length-1)){
                    console.log('item ' + i + ' is ' + 1);
                }else{
                    console.log('item ' + i + ' is ' + 0);
                }

            }
        }

        checkBraces(infoToParse);

    </script>
</body>
</html>

I was thinking about your goal though and I made this script that I think is doing what you are trying to do in making sure they are "correctly matched". This is OK: { () } and this is not OK: [(])

<!DOCTYPE html>
<html>
    <head>
        <title>Object</title>
    </head>
<body>

    <script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script>
    <script>

    //set the data to test
    var data = [ ")(){}", "[]({})", "([])", "{()[]}", "([)]" ];

    //identify the appropriate open/close pairs
    var pairs = {
        '{': '}', 
        '(': ')', 
        '[': ']'
    };

    //chek for a valid pair match
    //remove the match and return modified string
    function stepCheck(str){

        //set the vars
        var pattern = /[a-zA-Z0-9\s]/g, //remove letters, numbers, and spaces
            str = str.replace(pattern, ''), //no blank spaces
            open = str.charAt(0), //get the first character
            close = pairs[open], //get the appropriate closing character
            closeIndex = str.indexOf(close), //get the index of the closing character
            strLength = str.length, //get the length of the string
            part1 = '',
            part2 = '', 
            newStr = '';

        //if the index is -1 then no closing character was found
        // string is bad
        if(closeIndex === -1){
            return false;
        }

        //split the string into 2 parts
        //the first part is everything between the opening character and it's closing character
        //we will toss those out. The new string will be shorter by 2 characters
        part1 = str.substr(1, closeIndex - 1);

        //the second part is everything after, if anything at all
        if(part1.length < strLength){
            part2 = str.substr(closeIndex + 1);
        }

        //if either part has an odd number of characters then it's
        //a bad string. There has to be a pair for everything
        if(part1.length % 2 !== 0 || part2.length % 2 !== 0){
            return false;
        }

        //make a new string to return
        newStr = part1 + part2;

        //if the string is empty then all pairs have been matched and removed
        //otherwise return the new string
        if(newStr === ''){
            return true;
        }else{
            return newStr;
        }

    }


    //process the string until it returns true or false
    function cycle(str){

        //check the string
        var checked = stepCheck(str);

        //while 'checked' is not false
        while( checked ){

            // if it's true it's good
            if(checked === true){
                return true;
            }

            //if it's still a string then keep checking it
            checked = stepCheck(checked);
        }

        //'checked' returned false, it's bad
        return false;

    }



    //process each string/item in the array
    function readArray(arr){

        for(var i=0; i<arr.length; i++){
            console.log( 'Item ' + i + ' returns ' + cycle(arr[i]) );
        }

    }


    //set everything in motion
    readArray(data);


    </script>
</body>
</html>