Question

In: Computer Science

Create a method on the Iterator class called forEach, which appropriate behavior. This method should use...

  • Create a method on the Iterator class called forEach, which appropriate behavior.
  • This method should use next(), and should not use this._array.forEach!
  • Take note of what should happen if you call forEach twice on the same Iterator instance.
  • The estimated output is commented below
  • In javascript please
class Iterator {
  constructor(arr){
    this[Symbol.iterator] = () => this
    this._array = arr
    this.index = 0
  }

  next(){
    const done = this.index >= this._array.length
    const value = this._array[this.index++]
    return {done, value}
  }

  //YOUR WORK HERE
}


const arr = ["a","b","c","d","e"]
const it = new Iterator(arr)
it.forEach(item => console.log(item))

console.log("Let's try that again...")

it.forEach(item => console.log(item)) 
//produces no output

console.log("Extra credit: with indices...")

const it2 = new Iterator(arr)
it2.forEach((item, index) => console.log(item, index))


/*
a
b
c
d
e
Let's try that again...
Extra credit: with indices...
a 0
b 1
c 2
d 3
e 4
*/

Solutions

Expert Solution

Code in Javascript

class Iterator {
  constructor(arr){
    this[Symbol.iterator] = () => this
    this._array = arr
    this.index = 0
  }

  next(){
    const done = this.index >= this._array.length
    const value = this._array[this.index++]
    return {done, value}
  }

  forEach(func){
      while(this.index<this._array.length){
          const index = this.index;
          const item = this._array[index];
          func.call(this,item, index);
          this.index++;
      }
  }
}


const arr = ["a","b","c","d","e"]
const it = new Iterator(arr)
it.forEach(item => console.log(item))

console.log("Let's try that again...")

it.forEach(item => console.log(item)) 
// produces no output

console.log("Extra credit: with indices...")

const it2 = new Iterator(arr)
it2.forEach((item, index) => console.log(item, index))

Sample Output

Explanation

We are passing a function inside the forEach function and for every value from current index to the end we are calling this passed function. Let me know in the comments if you have any confusion.


Related Solutions

Create a preorder iterator for the class binarytree from the Python program below. class Binarytree: def...
Create a preorder iterator for the class binarytree from the Python program below. class Binarytree: def __init__(self, DataObject): self.data = DataObject self.parents = None self.left_child = None self.right_child = None @property def left_child(self): return self.__left_child @left_child.setter def left_child(self, node): self.__left_child = node if node is not None: node.parents = self @property def right_child(self): return self.__right_child @right_child.setter def right_child(self, node): self.__right_child = node if node is not None: node.parents = self def is_leafNode(self): if self.left_child is None and self.right_child is None:...
Create a class called FibGenerator with 3 methods: public int nthFib(int n). This method should call...
Create a class called FibGenerator with 3 methods: public int nthFib(int n). This method should call computeFibRecurse(n). private int computeFibRecurse(int n), which should recurse (that is, call itself) unless n is 1 or 2. If n is 1 or 2, the method should return 1. A main method that prints “STARTING”, then constructs a FibGenerator generator and then calls nthFib(), passing in interesting values. To look into this problem, you’re going to use software to analyze software. Add an instance...
Java Create a method to display a menu. When this method is called it should receive...
Java Create a method to display a menu. When this method is called it should receive the user's name, great the user, and ask them to make a selection. 1 - Change your name, 2 - Test your IQ, 3 - Display a table, 4 - Play a game, 5 - Exit.
Animal class Create a simple class called Animal instantiated with a name and a method toString...
Animal class Create a simple class called Animal instantiated with a name and a method toString which returns the name. Cat class Create a simple class Cat which extends Animal, but adds no new instance variable or methods. RedCat class Create a simple class RedCat which extends Cat, but adds no new instance variable or methods. WildCardTester class Create a class with the main method and methods addCat, deleteCat and printAll as follows. addCat method Has two parameters, an ArrayList...
language is java Use method overloading to code an operation class called CircularComputing in which there...
language is java Use method overloading to code an operation class called CircularComputing in which there are 3 overloaded methods as follows: computeObject(double radius)-compute area of a circle computeObject(double radius, double height)-compute area of a cylinder computeObject(double radiusOutside, double radiusInside, double height)-compute volume of a cylindrical object These overloaded methods must have a return of computing result in each Then override toString() method so it will return the object name, the field data, and computing result Code a driver class...
Create a new class called Account with a main method that contains the following: • A...
Create a new class called Account with a main method that contains the following: • A static variable called numAccounts, initialized to 0. • A constructor method that will add 1 to the numAccounts variable each time a new Account object is created. • A static method called getNumAccounts(). It should return numAccounts. Test the functionality in the main method of Account by creating a few Account objects, then print out the number of accounts
Create method addUserInput Write a method called addUserInput(). The method should ask the user to input...
Create method addUserInput Write a method called addUserInput(). The method should ask the user to input two integers (one by one), add the two integers, and return the sum. By using java.util.Scanner to get user input; The method may not compile due to Scanner Class which need to add a "throws" statement onto the end of the method header because some lines may throw exceptions Refer to the Java API documentation on Scanner to figure out which specific Exception should...
Java Palindrome Use StringBuilder concept to create a palindrome checker.   Method should be called pCheck. Must...
Java Palindrome Use StringBuilder concept to create a palindrome checker.   Method should be called pCheck. Must use var-arg concept.   Class name for this program is Palindrome.   Must pass this test:: public class PalindromeTest { public static void main(String[] args) { Palindrome palindrome = new Palindrome(); boolean answer = palindrome.pCheck("racecar", "Bell", "elle", "bunny"); System.out.println(“These are palindromes: " + answer); } }
Create a file called grocery.ts. It should have a definition of a class with the obvious...
Create a file called grocery.ts. It should have a definition of a class with the obvious name Grocery. The class should have some basic attributes such as name, quantity, etc. Feel free to add any other attributes you think will be necessary. Add few grocery items to an array of groceries, such as milk, bread, and eggs, along with some quantities (i.e. 3, 6, 11). Display these grocery items as HTML output. The output of this assignment will be grocery.ts...
- Class DiscountPolicy is an abstract class with a method called computeDiscount, which returns the discount...
- Class DiscountPolicy is an abstract class with a method called computeDiscount, which returns the discount for the purchase of items. DiscountPolicy knows the name of the item and its cost as well as the number of items being purchased. - Class BulkDiscount, derived from DiscountPolicy, has two fields, minimum and percentage. computeDiscount method will return the discount based on the percentage applied, if the quantity of items purchased is more than minimum. For example: if minimum is 3 and...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT