js try not to use if to write code

Example 1: Counting odd numbers in an array

Suppose we have an array of integers arrayOfIntegers , and now we need to count the number of odd numbers in it:

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

use if

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

});

console.log(counter);

 

Instead of if, use reduce and forEach

const arrayOfIntegers = [1, 4, 5, 9, 0, -1, 5];
let counter = 0;
arrayOfIntegers.forEach((integer) => {
  const remainder = Math.abs(integer % 2);
  counter += remainder;
});

console.log(counter);

console.log(
  arrayOfIntegers.reduce(
    (pre, cur) => pre + Math.abs(cur) % 2
  )
)


When we don't use if, we cleverly take advantage of the properties of odd and even numbers, and their remainders when divided by 2 are 0 and 1, respectively.

 

Example 2: Determining weekdays and weekends

Given a date (such as new Date() ), determine whether it is a weekday or a weekend, and return "weekend" and "weekday" respectively.

use if

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()));

no 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()));

 

Did you find that there is actually some information implicit in the if statement? It tells us which day is a weekend and which day is a weekday. So, to get rid of the if statement, we just need to write this information into the weekendOrWeekday.labels object and use it directly.

Example 3: doubler function

Write a doubler function that performs different operations depending on the type of the parameter:

  • If the argument is a number, multiply by 2(ie  5 => 10-10 => -20);

  • If the argument is a string, each character is repeated 2 times (ie  'hello' => 'hheelloo');

  • If the parameter is a function, it is called 2 times;

  • If the parameter is an array, call the doubler function with each element as a parameter

  • If the argument is an object, call the doubler function with each property value as an argument

use switch

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');
  }),
);

no switch

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');
  }),
);

 

It can be seen that I bound the operation corresponding to each parameter type to doubler.operationsByType, so that the doubler function can be implemented without a switch statement.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325080523&siteId=291194637