Interface example

// interface for a sequence used by function logFive: // next() to know if next elem exists // curr() to get current elem function logFive(seqObj) { for (var i = 0; i < 5; i++) { console.log(seqObj.curr()); if (!seqObj.next()) { return false; } } } // ArraySeq => constructor for an object that wraps an array function ArraySeq(array) { this.pos = 0; this.arr = array; } ArraySeq.prototype.next = function() { if (this.arr[this.pos+1]!==null){ this.pos++; return true; } return false; }; ArraySeq.prototype.curr = function() { return this.arr[this.pos]; }; // RangeSeq => constructor for an object that iterates over a range of integers function RangeSeq(from, to) { this.val = from; this.from = from; this.to = to; } RangeSeq.prototype.next = function() { if (this.val < this.to){ this.val++; return true; } return false; }; RangeSeq.prototype.curr = function() { return this.val; }; logFive(new ArraySeq([1,2])); // → 1 // → 2 logFive(new RangeSeq(100, 1000)); // → 100 // → 101 // → 102 // → 103 // → 104
Design an interface that abstracts iteration over a collection of values. An object that provides this interface represents a sequence, and the interface make it possible for code that uses such an object to iterate over the sequence, looking at the element values it is made up of and having some way to find out when the end of the sequence is reached.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.