Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

技巧篇:不用if语句撸代码 #27

Open
ttop5 opened this issue Aug 8, 2018 · 0 comments
Open

技巧篇:不用if语句撸代码 #27

ttop5 opened this issue Aug 8, 2018 · 0 comments

Comments

@ttop5
Copy link
Owner

ttop5 commented Aug 8, 2018

最近看到网上一个比较有意思的运动:抵制if运动,他们的口号是:Less IFs, more power。于是找了一些相关文章看了一下,略有启发,以下是其中的一篇。(非全文翻译)

原文链接:https://edgecoders.com/coding-tip-try-to-code-without-if-statements-d06799eed231


..... (略去废话)

Challenge 1:统计数组中的奇数

假设有一个整数数组,我们想要统计奇数的个数,以下是测试用例:

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

使用if语句:

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

不用if语句:

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

在不用if语句时,我们巧妙的利用了奇数和偶数的特性:奇数%2等于1,偶数%2等于0。

Challenge 2:判断周末和工作日

给定个日期(如:new Date()),判断是周末还是工作日,分别返回“weekend”或者“weekday”。

使用if语句:

const weekendOrWeekday = (inputDate) => {
  const day = inputDate.getDay();
  if (day === 0 || day === 6) {
    return 'weekend';
  } 
  
  return 'weekday';
  // 或使用三元表达式:
  // return (day === 0 || day === 6) ? 'weekend' : 'weekday';
};
console.log(weekendOrWeekday(new Date()));

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

再不用if语句时,我们需要把哪天是周末哪天是工作日这些信息写入一个对象中,然后直接使用它。

Challenge 3:doubler函数

写一个doubler函数,它会根据参数的类型,进行不同的操作:

  • 如果参数是数字,则乘以2(i.e. 5 => 10, -10 => -20);
  • 如果参数是字符串,则每个字符重复2次 (i.e. 'hello' => 'hheelloo');
  • 如果参数是函数,则调用2次;
  • 如果参数是数组,则将每一个元素作为参数,调用doubler函数;
  • 如果参数是对象,则将每个属性值作为参数,调用doubler函数。

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

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

同理,在不用switch语句时,我们依然是不用的类型和对应操作存到对象当中,然后该对象用于选择正确的操作并使用原始输入调用它。

@ttop5 ttop5 added this to the 2018年08月 milestone Aug 8, 2018
@ttop5 ttop5 self-assigned this Aug 8, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant