BugBuddy
BugBuddy

Reputation: 606

Making use of ECMAScript 6 features in Javascript; When to use fat arrow functions, etc.?

I'm doing the Udemy course ES6 Javascript: The Complete Developer's Guide Stephen Grider on my own. This course is my first exposure to javascript. It contains an interesting (to me) exercise on detecting balanced parentheses. I wrote a function with the features I would expect, but I did not use fat arrow functions. I probably did not use other ECMAScript 6 features that I could have used. I would like any suggestions on improving my code.

function balancedParens(inputString){
  const errMsg1 = 'ERROR: expression will NEVER be balanced';
  const errMsg2 = 'ERROR: unbalanced!';
  const successMsg = 'parens are balanced.';
  const chars = inputString.split("");
  let count = 0;
  for ( let i = 0; i < chars.length; ++i ) {
    if ( count < 0 ) { console.log(errMsg1); return false; }
    if ( chars[i] === "(" ) { ++count; }
    else if ( chars[i] === ")" ) { --count; }
  }
  if ( count < 0 ) { console.log(errMsg1); return false; }
  else if ( count == 0 ) { console.log(successMsg); return true; }
  else { console.log(errMsg2); return false; }
}

balancedParens("()()(i)"); //correctly returns true
balancedParens("()()())"); //correctly returns false

My function detects parens that can never be balanced and bails out early, which is something the example from the course did not do. I want to retain this feature as I refactor and improve my code.

The course strongly recommends against using for-loops, but I couldn't think of a better way to implement my features. And I couldn't see how using fat arrow functions would improve the code. So I am looking forward to suggestions and feedback.

Upvotes: 1

Views: 86

Answers (4)

Monica Acha
Monica Acha

Reputation: 1086

Reduce function can be used to iterate over the string and return a single value.reduce

Arrow functions are used for the lexical scoping of this.Arrow functions

Upgradation of ES5 features- bind,call and apply.

 const errMsg1 = 'ERROR: expression will NEVER be balanced';
const errMsg2 = 'ERROR: unbalanced!';
const successMsg = 'parens are balanced.';
balancedParanthesis = (string) => {
    return string.split("").reduce((count, char) => {  //returns boolean expression
    
        if(count < 0 ){return count;}
        else if(char === '('){++count;}
        else if(char === ')'){ --count;}
        return count;       
    },0)
}
    
let count = balancedParanthesis("()()");
//let count = balancedParanthesis("((())");
//let count = balancedParanthesis(")((())");
if ( count < 0 ) { console.log(errMsg1); }
else if ( count == 0 ) { console.log(successMsg);  }
else { console.log(errMsg2); }

Upvotes: 0

Jackson Lenhart
Jackson Lenhart

Reputation: 640

I think your code is fine. It is straight-forward and easy to understand. However it is definitely not what the current javascript hipsters would think is cool or whatever.

Unfortunately w/o using a traditional loop structure like a for loop, you cannot exit early when parens can never be balanced. So honestly your function is probably more efficient than what they're looking for. But generally speaking javascript hipsters don't really care about code efficiency.

This might be more what they're looking for:

const balancedParens = inputString =>
        
        // We don't need curly brackets here because we're doing everything
        // on one "line" and just returning
    	inputString.split('')

        // Reduce is the substitute for your for loop here.
        // It iterates over each character and stores the return value in "sum"
        // on each iteration
    	.reduce((sum, char) => {
    		if (char === '(') return sum + 1;
    		else if (char === ')') return sum - 1;
    		else return sum;

        // This comparison makes the entire function return true if
        // our reduce resulted in zero, otherwise false
        }, 0) === 0;


const logResult = result =>
    result ? console.log('parens are balanced.')
    : console.log('ERROR: unbalanced!');
    
logResult(balancedParens('()()(i)'));
logResult(balancedParens('()()())'));

If you're not familiar with the reduce function on the array, check it out here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

It is a higher-order function (meaning a function that takes a function as one of it's arguments). This is a common use case for the fat arrows simply because the notation ends up being much more terse.

Note: I might be skeptical about any course that "strongly recommends against" for loops. But maybe they're just trying to get you to use the new JS features.

Upvotes: 1

Adam
Adam

Reputation: 1754

I'm not sure on the context, but there's no reason to believe that for loops are inherantly bad. You might want to be aware of the performance impact of nesting for loops but classical for loops are used often enough and there's no reason not to use them.

As far as arrow functions go, in your case the advantages might be that your code is more concise and easier to read. Arrow functions are just a shorthand way of writing functions. More often than not, readability is more important than the slim performance improvements you may or may not get from using arrow functions, streams and functional programming features provided in ES6.

For your case, it might be nice to use some arrow functions to make your code more concise. So you could replace the for loop by streaming the char array and using .forEach.

Upvotes: 0

squeekyDave
squeekyDave

Reputation: 962

My personal opinion is that arrow functions work best when you do not have to bind this to the current function context. At this point this will not make any sense to you but arrow functions do not have their own this keyword which means the value of this will be taken outside the lexical scope of the arrow function. They are good for callbacks aswell( the same rule above applies ), also when you need to write a short expression, it looks neat. It all depends on you just make sure you know how this behaves and you will be ok.

Upvotes: 0

Related Questions