break相当于循环中的GOTO,需避免使用。

下面是一个break使用例子。
找出第一个months小于7的项目。

const cats = [
  { name: 'Mojo',    months: 84 },
  { name: 'Mao-Mao', months: 34 },
  { name: 'Waffles', months: 4 },
  { name: 'Pickles', months: 6 }
]
const isKitten = cat => cat.months < 7
var firstKitten
for (var i = 0; i < cats.length; i++) {
  if (isKitten(cats[i])) {
    firstKitten = cats[i]
    break
  }
}

类似的例子,找出前五个项目。

var first5Kittens = []
// old-school edge case kitty loop
for (var i = 0; i < cats.length; i++) {
  if (isKitten(cats[i])) {
    first5Kittens.push(cats[i])
    if (first5Kittens.length >= 5) {
      break
    }
  }
}

对上面的例子进行改造。
用函数封装下。用limit来代替5,predicate来代替isKitten,list来代替cats。然后把这些作为函数的参数。

const takeFirst = (limit, predicate, list) => {
  const newList = []
  
  for (var i = 0; i < list.length; i++) {
    if (predicate(list[i])) {
      newList.push(list[i])
  
      if (newList.length >= limit) {
        break
      }
    }
  }
  
  return newList
}

使用递归形式来表示循环,跳出递归即break。


const takeFirst = (limit, predicate, list, i = 0, newList = []) => {
  const isDone = limit <= 0 || i >= list.length
  const isMatch = isDone ? undefined : predicate(list[i])
  
  if (isDone) {
    return newList
  } else if (isMatch) {
    return takeFirst(limit - 1, predicate, list, i + 1, [...newList, list[i]])
  } else {
    return takeFirst(limit, predicate, list, i + 1, newList)
  }
}

使用第三方库Lazy.js来实现这个需求。

const result = Lazy(cats)
  .filter(isKitten)
  .take(5)

参考:
https://hackernoon.com/rethinking-javascript-break-is-the-goto-of-loops-51b27b1c85f8

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-24
  • 2021-12-29
  • 2022-12-23
  • 2021-12-15
  • 2021-12-02
  • 2022-12-23
猜你喜欢
  • 2021-07-21
  • 2022-12-23
  • 2021-10-14
  • 2021-07-10
  • 2022-01-29
相关资源
相似解决方案