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

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:

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

Last updated

Was this helpful?