lbwa / set.sh-stale

✍A place which is used to share my programming experiences in Chinese. 一个分享代码经历的地方。
https://set.sh
0 stars 0 forks source link

JS 迭代器实现 #25

Open lbwa opened 5 years ago

lbwa commented 5 years ago
function myIterator (arr) {
  let __index = 0
  return {
    // 迭代器对象核心
    // arr[__index++] 为示例目标值访问接口,可替换为其他类型值访问接口来实现其他类型迭代
    next () {
      return __index < arr.length ?
        {value: arr[__index++], done: false} : 
        {value: undefined, done: true}
    }
  }
}

const it = myIterator([1, 2, 3, 4])

// output
const c = document.createElement.bind(document)
function createFragment (result) {
  const fragment = c('div')
  fragment.innerText = result
  return fragment
}

(function insert () {
  let i = 5
  const chip = c('div')
  while (i--) {
    chip.appendChild(createFragment(JSON.stringify(it.next())))
  }
  document.body.appendChild(chip)
})()

Play on the playground