@Bubbling Horse Tree

The original address of the question bank: http://csbin.io/iterators

IteratorsIterators

Challenge 1

question:

A) Create a for loop that iterates over an array and returns the sum of all elements of the array.

B) Create a functional iterator that traverses each element of the incoming array, one element at a time.

answer:

 // 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'

Challenge 2

question:

Create an iterator with a next method attached. When .next is called, this iterator returns the elements of the array one by one.

answer:

 // 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

Challenge 3

question:

Write the code to iterate over an entire array using the nextIterator function above, and sum it up.

answer:

 // 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

Challenge 4

question:

Create an iterator with a next method attached. When .next is called, it returns each element of the set collection passed in.

answer:

 // 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'

Challenge 5

question:

Create an iterator with a next method attached. When .next is called, it returns an array with two elements (the first is the subscript, and the second is the array element corresponding to the subscript).

answer:

 // 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']

Challenge 6

question:

Create an iterator. When its .next method is called, it returns each word in a sentence-like string.

(Hint: use regular expressions!)

Then mount this operation as a method on the prototype chain of the constructor Words.

(Hint: research Symbol.iterator!)

answer:

 // 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'

Challenge 7

question:

Create a function. This function traverses the incoming array and returns the string result concatenated by the corresponding traversed element and the string "was found after index x", where x is the previous subscript.

Note: For the first element, it should return "It is the first".

answer:

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

Challenge 8

question:

Write a function. It will console.log print "hello there" or "gibberish" every three seconds, depending on whether the value passed to the function is "english".

Do not use loops of any kind and call createConversation only once.

answer:

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

Challenge 9

question:

Use async/await to console.log print a sentence composed of the noun noun and the verb verb, where the non-async function will receive a noun noun, concatenate with a hard-coded verb verb, and return to the async function after three seconds. After the asynchronous function receives the data, it will console.log to print the corresponding data. An asynchronous function can only be called once, pass in a noun noun to witness its execution!

answer:

 //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")


冒泡的马树
194 声望14 粉丝

曾痴迷于赛博朋克世界的代码玩家一枚,