JavaScript專項演算法題(7):Iterators迭代器

冒泡的馬樹發表於2022-05-14

@冒泡的馬樹

題庫原地址:http://csbin.io/iterators

Iterators迭代器

挑戰1

問題:

A) 建立一個for迴圈,用於遍歷陣列,返回陣列的所有元素的總和。

B) 建立一個函式式迭代器,呼叫時遍歷傳入的陣列的每一個元素,每次一個元素。

題解:

// CHALLENGE 1

function sumFunc(arr) {
  // YOUR CODE HERE
  let sum = 0
  for(let i = 0; i < arr.length; i++) {
    sum += arr[i]
  }
  return sum
}

// Uncomment the lines below to test your work
const array = [1, 2, 3, 4];
console.log(sumFunc(array)); // -> should log 10

function returnIterator(arr) {
  // YOUR CODE HERE
  let i = 0
  const inner = () => {
    const element = arr[i]
    i++
    return element
  }
  return inner
}

// Uncomment the lines below to test your work
const array2 = ['a', 'b', 'c', 'd'];
const myIterator = returnIterator(array2);
console.log(myIterator()); // -> should log 'a'
console.log(myIterator()); // -> should log 'b'
console.log(myIterator()); // -> should log 'c'
console.log(myIterator()); // -> should log 'd'

挑戰2

問題:

建立一個附有next方法的迭代器。當.next被呼叫時,此迭代器會逐個返回陣列內的元素。

題解:

// CHALLENGE 2

function nextIterator(arr) {
  // YOUR CODE HERE
  let i = 0
  const inner = {
    next: () => {
      const element = arr[i]
      i++
      return element
    }
  }
  return inner
}

// Uncomment the lines below to test your work
const array3 = [1, 2, 3];
const iteratorWithNext = nextIterator(array3);
console.log(iteratorWithNext.next()); // -> should log 1
console.log(iteratorWithNext.next()); // -> should log 2
console.log(iteratorWithNext.next()); // -> should log 3

挑戰3

問題:

編寫程式碼,使用上方的nextIterator函式遍歷一整個陣列,然後求和。

題解:

// CHALLENGE 3

function sumArray(arr) {
  // YOUR CODE HERE
  // use your nextIterator function
  const iteratorWithNext = nextIterator(arr)
  let sum = 0
  let item 
  while(item = iteratorWithNext.next()) {
    sum += item
  }
  return sum
}

// Uncomment the lines below to test your work
const array4 = [1, 2, 3, 4];
console.log(sumArray(array4)); // -> should log 10

挑戰4

問題:

建立一個附有next方法的迭代器。當呼叫.next時,它會返回傳入的set集合的每一個元素。

題解:

// CHALLENGE 4

function setIterator(set) {
  // YOUR CODE HERE
  // Solution One:
  // let i = 0
  // const arr = [...set]
  // return {
  //   next: () => arr[i++]
  // }
  // Solution Two:
  const newSet = set[Symbol.iterator]()
  return {next: () => newSet.next().value}
}

// Uncomment the lines below to test your work
const mySet = new Set('hey');
const iterateSet = setIterator(mySet);
console.log(iterateSet.next()); // -> should log 'h'
console.log(iterateSet.next()); // -> should log 'e'
console.log(iterateSet.next()); // -> should log 'y'

挑戰5

問題:

建立一個附有next方法的迭代器。當呼叫.next時,它會返回帶有兩個元素的陣列(第一個為下標,第二個為下標對應的陣列元素)。

題解:

// CHALLENGE 5

function indexIterator(arr) {
  // YOUR CODE HERE
  let i = 0
  return {
    next: () => {
      const element = arr[i]
      const index = i
      i++
      return [index, element]
    }
  }
}

// Uncomment the lines below to test your work
const array5 = ['a', 'b', 'c', 'd'];
const iteratorWithIndex = indexIterator(array5);
console.log(iteratorWithIndex.next()); // -> should log [0, 'a']
console.log(iteratorWithIndex.next()); // -> should log [1, 'b']
console.log(iteratorWithIndex.next()); // -> should log [2, 'c']

挑戰6

問題:

建立一個迭代器。在它的.next方法被呼叫時,它會返回一個句子型字串中的每一個單詞。

(提示:使用正規表示式!)

然後將此操作當成一個方法掛載到構建函式Words的原型鏈上。

(提示:研究Symbol.iterator!)

題解:

// CHALLENGE 6

function Words(string) {
  this.str = string;
}

Words.prototype[Symbol.iterator] = function() {
  // YOUR CODE HERE
  const reg = /\w+/g
  const strArr = this.str.match(reg)
  let index = 0
  return {
    next: () => 
      (index < strArr.length) ? 
        { done: false, value: strArr[index++] } :
        { done: true, value: undefined }
  }
}

// Uncomment the lines below to test your work
const helloWorld = new Words('Hello World');
for (let word of helloWorld) { console.log(word); } // -> should log 'Hello' and 'World'

挑戰7

問題:

建立一個函式。此函式會遍歷傳入的陣列,返回對應的遍歷元素和字串“was found after index x”拼接而成的字串結果,其中的x是前一個下標。

注意:對於第一個元素,它應該返回“It is the first”。

題解:

// CHALLENGE 7

function valueAndPrevIndex(array){
  const iteratedArray = array[Symbol.iterator]()
  let index = 0
  return {
    sentence: () => {
      if (index == 0) {
        iteratedArray.next()
        index++
        return `It is the first`
      } else {
        const result = `${iteratedArray.next().value} was found after index ${index - 1}`
        index++
        return result
      }
    }
  }
}

const returnedSentence = valueAndPrevIndex([4,5,6])
console.log(returnedSentence.sentence());
console.log(returnedSentence.sentence());
console.log(returnedSentence.sentence());

挑戰8

問題:

編寫一個函式。它會每三秒鐘console.log列印“hello there”或“gibberish”,取決於傳入函式的值是否為“english”。

請勿使用任何形式的迴圈且請僅呼叫createConversation一次。

題解:

//CHALLENGE 8

function* createConversation(string) {
  let output = ''
  if (string === 'english') {
    output = 'hello there'
  } else {
    output = 'gibberish'
  }
  yield setInterval(() => {console.log(output)}, 3000)
}

createConversation('english').next();

挑戰9

問題:

使用async/await來console.log列印一個由名詞noun和動詞verb構成的句子,其中非非同步函式會接收一個名詞noun,與一個硬編碼的動詞verb拼接,在三秒後返回給非同步函式。非同步函式接收到資料後,會console.log列印相應資料。非同步函式僅能呼叫一次,傳入一個名詞noun見證它的執行吧!

題解:

//CHALLENGE 9
function waitForVerb(noun) {
  return new Promise(resolve => {
    const verb = 'barks'
    setTimeout(() => resolve(`${noun} ${verb}`), 3000)
  })
}

async function f(noun) {
  const sentence = await waitForVerb(noun)
  console.log(sentence)
}

f("dog")

相關文章