Skip to content

Instantly share code, notes, and snippets.

@zaneli
Created July 28, 2013 13:34
Show Gist options
  • Save zaneli/6098597 to your computer and use it in GitHub Desktop.
Save zaneli/6098597 to your computer and use it in GitHub Desktop.
「CoffeeScript によるデザインパターン(Iterator)」ブログ用
class @ArrayIterator
constructor: (@array) ->
@index = 0
hasNext: ->
@index < @array.length
item: ->
@array[@index]
nextItem: ->
value = @array[@index]
@index += 1
value
@merge = (array1, array2) ->
merged = []
iterator1 = new ArrayIterator(array1)
iterator2 = new ArrayIterator(array2)
while iterator1.hasNext() and iterator2.hasNext()
if iterator1.item() < iterator2.item()
merged.push iterator1.nextItem()
else
merged.push iterator2.nextItem()
while iterator1.hasNext()
merged.push iterator1.nextItem()
while iterator2.hasNext()
merged.push iterator2.nextItem()
merged
class @ArrayIterator
constructor: (@array) ->
@index = 0
hasNext: ->
@index < @array.length
item: ->
@array[@index]
nextItem: ->
value = @array[@index]
@index += 1
value
package views
import org.specs2.mutable.Specification
import play.api.test.TestServer
import play.api.test.Helpers.{ running, HTMLUNIT }
class IteratorSpec extends Specification {
private val testPort = 3333
"Iterator" should {
"iterate some items" in {
running(TestServer(testPort), HTMLUNIT) { browser =>
browser.goTo(s"http://localhost:${testPort}/iterator")
browser.executeScript("""
var array = ["red", "green", "blue"];
var i = new ArrayIterator(array);
while (i.hasNext()) console.log("item: " + i.nextItem());
""")
browser.$("#__console_log").getValue must_== """item: red
item: green
item: blue
"""
browser.$("#__console_warn").getValue must beNull
}
}
"iterate no item" in {
running(TestServer(testPort), HTMLUNIT) { browser =>
browser.goTo(s"http://localhost:${testPort}/iterator")
browser.executeScript("""
var array = [];
var i = new ArrayIterator(array);
while (i.hasNext()) console.log("item: " + i.nextItem());
""")
browser.$("#__console_log").getValue must beNull
browser.$("#__console_warn").getValue must beNull
}
}
"merge some items" in {
running(TestServer(testPort), HTMLUNIT) { browser =>
browser.goTo(s"http://localhost:${testPort}/iterator")
browser.executeScript("""
var array1 = [1, 3, 5, 7, 9];
var array2 = [2, 6, 10, 12];
console.log(merge(array1, array2));
""")
browser.$("#__console_log").getValue must_== """1,2,3,5,6,7,9,10,12
"""
browser.$("#__console_warn").getValue must beNull
}
}
"merge no item" in {
running(TestServer(testPort), HTMLUNIT) { browser =>
browser.goTo(s"http://localhost:${testPort}/iterator")
browser.executeScript("""
console.log(merge([], []));
""")
browser.$("#__console_log").getValue must_== ""
browser.$("#__console_warn").getValue must beNull
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment