Coding Tip: Try to Code Without If-statements

For now, try to avoid using if statements as much as possible to implement our business

You may be wondering what’s the advantage of not using if? Well, there may be no obvious benefit, just a different way of thinking about problems. There is nothing wrong with if-else, but in some cases a lot of if-else can reduce code readability. Here are some examples to show you how.

Challenge #1: Count how many odd numbers there are in the numeric array

Given an array of integer types, count the number of odd numbers in the array

const arrayOfIntegers = [1, 4, 5, 9, 0, -1, 5];Copy the code

If implementation

let counter = 0; arrayOfIntegers.forEach((integer) => { const remainder = Math.abs(integer % 2); if (remainder === 1) { counter++; }}); console.log(counter);Copy the code

With the if

let counter = 0; arrayOfIntegers.forEach((integer) => { const remainder = Math.abs(integer % 2); // The remainder of an even number divided by 2 is zero, and the remainder of an odd number is 1. }); console.log(counter);Copy the code

Note: In both of the above examples, forEach is a mutable way to change an array, contrary to the immutable idea of functional programming, and is not the focus of this article. In comparison, the implementation of the if statement may be more compatible with array elements that are decimals. If the array elements are of floating point type, the second example will not work.

Challenge #2: Determine whether a date is a weekend or a weekday

Implement a function that takes the Date object new Date() as input and returns whether the day is a weekday or a weekend, depending on the Date.

If implementation

const weekendOrWeekday = inputDate => {
  const day = inputDate.getDay();
  if (day === 0 || day === 6) {
    return 'weekend';
  }

  return 'weekday';
  // Or, for ternary fans:
  // return (day === 0 || day === 6) ? 'weekend' : 'weekday';
};
console.log(weekendOrWeekday(new Date()));Copy the code

With the if

const weekendOrWeekday = (inputDate) => {
  const day = inputDate.getDay();
  return weekendOrWeekday.labels[day] ||
         weekendOrWeekday.labels['default'];
};
weekendOrWeekday.labels = {
  0: 'weekend',
  6: 'weekend',
  default: 'weekday'
};
console.log(weekendOrWeekday(new Date()));Copy the code

Notice that the numbers in the if statement represent which day is the weekend, so the distribution of conditions is scattered. What we need to do is to match the numbers to the weekend or weekday type. As in Example 2, we can use an object or map to store the corresponding relationship.

Comparing the two examples above, it is clear that the non-IF code implementation is much more readable and extensible

Challenge #3: The Doubler function (here be Dragons)

Implement a Doubler function that, depending on the input, does the following:

  1. If the input isnumberType, double (5 => 10, -10 => -20)
  2. If the input isstringType, repeating each character (‘hello’ => ‘hheelloo’)
  3. If the input isfunctionType that calls a function that executes twice
  4. If the input isarrayType for each element of the arraydoublerTo deal with
  5. If the input isobjectType, for each property of the objectdoublerTo deal with

The switch to realize

const doubler = (input) => { switch (typeof input) { case 'number': return input + input; case 'string': return input .split('') .map(letter => letter + letter) .join(''); case 'object': Object.keys(input) .map(key => (input[key] = doubler(input[key]))); return input; case 'function': input(); input(); }}; console.log(doubler(-10)); console.log(doubler('hey')); console.log(doubler([5, 'hello'])); console.log(doubler({ a: 5, b: 'hello' })); console.log( doubler(function() { console.log('call-me'); }));Copy the code

The switch to realize

const doubler = (input) => { return doubler.operationsByType[typeof input](input); }; doubler.operationsByType = { number: (input) => input + input, string: (input) => input .split('') .map((letter) => letter + letter) .join(''), function: (input) => { input(); input(); }, object: (input) => { Object.keys(input) .map((key) => (input[key] = doubler(input[key]))); return input; }}; console.log(doubler(-10)); console.log(doubler('hey')); console.log(doubler([5, 'hello'])); console.log(doubler({ a: 5, b: 'hello' })); console.log( doubler(function() { console.log('call-me'); }));Copy the code

Similar to Challenge #2, the conditional values are aggregated together for uniform processing.

conclusion

If there are too many if-else conditions, the conditions are processed in a centralized manner (object is used to store their corresponding relationships — conditions are used as keys and processes are used as values). The benefit is that it is easier to add or remove a condition, making the code more readable, and advocating the use of key-value correspondence instead of some if-else condition judgments.