What is Clean Code

You Care

"Clean code always looks like it was written by someone who cares."

Example

LeetCode Problem 20

Code Example I found on Github

Bad Code (Spaghetti)

/**
 * @param {string} s
 * @returns {boolean}
 */
var isValid = function(s) {

  if ((s.length % 2 === 1) || (s.length === 0)) {
      return false;
  }

  var brackets = [],
      openBracketsMapping = {
        '(': ')',
        '[': ']',
        '{': '}'
      },
      chars = s.split(''),
      currentChar = '',
      couple = '';

  for (var i = 0; i < chars.length; i++) {
    currentChar = chars[i];
    if (currentChar in openBracketsMapping) {
      brackets.push(currentChar);
    } else {
      if (openBracketsMapping[brackets.pop()] !== currentChar) {
         return false;
      } else {
        continue;;
      }
    }
  }

  if (brackets.length === 0) {
      return true;
  }
  return false;
};

Clean Code

/**
 * @param {string} s
 * @returns {boolean}
 */
var openBracketMapping = {
    '(': ')',
    '[': ']',
    '{': '}'
};
var bracketStack;

var isValid = function(s) {

    if (isImpossibleValid(s)) {
        return false;
    }

    return isValidCheck(s);

};

function isValidCheck(s) {

    initBracketStack();

    var chars = s.split('');
    for(var i = 0; i < chars.length; i++) {

        var c = chars[i];

        if (isOpenBracket(c)) {
            getNewOpenBracket(c);
        } else if (!isCorrectCloseBracket(c)) {
            return false;
        }

    }

    return isBracketStackEmpty();

}

function isImpossibleValid(s) {
    var isLengthOdd = (s.length % 2 === 1);
    var isEmpty = (s.length === 0);
    return  isLengthOdd || isEmpty;
}

function initBracketStack() {
    bracketStack = [];
}

function getNewOpenBracket(c) {
    bracketStack.push(c);
}

function isOpenBracket(c) {
    return c in openBracketMapping;
}

function isCorrectCloseBracket(c) {

    var stackTop = bracketStack.pop();
    var expectedChar = openBracketMapping[stackTop];

    return expectedChar === c;

}

function isBracketStackEmpty() {
    return bracketStack.length === 0;
}

Question

  • Please explain the code, which one is easier?
  • Any funny thing found in the code?
  • If you want to support quotation marks including "" and '', how?

Tip

The easiest way to test the code is to use Node. Install Node first (link is here), save your file then run follow command:

$ node main.js # change to your own filename

You can use console.log("string") to print things out.