Skip to content
Browse files

streams are interesting

  • Loading branch information...
1 parent e5182a5 commit 9a629682ed975ce0b31640ffc2f11cab81148c4c @sconover committed Feb 2, 2011
Showing with 96 additions and 0 deletions.
  1. +44 −0 lib/stream_functions.js
  2. +22 −0 spec/stream/detect_spec.js
  3. +27 −0 spec/stream/spec_helper.js
  4. +3 −0 spec/stream/suite.js
View
44 lib/stream_functions.js
@@ -0,0 +1,44 @@
+StreamFunctions = function(features) {
+ var terminator = features.eof || {}
+ var functionsForExport = {}
+
+ function eof(thing) {
+ return thing === terminator
+ }
+ functionsForExport.eof = eof
+
+
+ function detect(stream, matcher) {
+ var candidate = null
+ while (!eof(candidate=stream.next())) {
+ if (matcher(candidate)) return candidate
+ }
+ return terminator
+ }
+ functionsForExport.detect = detect
+ //
+ // function select(iterator, matcher) {
+ // return {
+ // var empty = {}
+ // var nextMatch == features.nothing()
+ //
+ // function advanceIfNecessary() {
+ // if (nextMatch === empty) nextMatch = detect(iterator, matcher)
+ // return nextMatch
+ // }
+ //
+ // hasNext: function() {
+ // return !(advanceIfNecessary() === terminator)
+ // },
+ // next: function() {
+ // if (!hasNext()) throw "after end"
+ // var result = advanceIfNecessary()
+ // nextMatch = empty
+ // return result
+ // }
+ // }
+ // }
+ // functionsForExport.select = select
+
+ return {functions:functionsForExport}
+}
View
22 spec/stream/detect_spec.js
@@ -0,0 +1,22 @@
+require("./spec_helper.js");
+
+describe("detect", function() {
+
+ var f = StreamFunctions({eof:EOF}).functions
+
+ it("finds the next occurrence in a stream and then stops", function(){
+ var stream = arrayStream([1,2,3,4,5,6])
+ expect(f.detect(stream, function(item){return item %2==0})).toEqual(2)
+ expect(f.detect(stream, function(item){return item %2==0})).toEqual(4)
+ expect(f.detect(stream, function(item){return item %2==0})).toEqual(6)
+ expect(f.eof(f.detect(stream, function(item){return item %2==0}))).toEqual(true)
+ })
+
+ it("returns eof if there's no match", function(){
+ var stream = arrayStream([1,2,3,4,5,6])
+ var result = f.detect(stream, function(item){return item == 99})
+ expect(f.eof(result)).toEqual(true)
+ })
+
+})
+
View
27 spec/stream/spec_helper.js
@@ -0,0 +1,27 @@
+require.paths.push("spec")
+require.paths.push("lib")
+
+require("../../../jasmine-node/lib/jasmine")
+
+for(var key in jasmine) {
+ global[key] = jasmine[key]
+}
+
+require("stream_functions")
+
+EOF = "THIS IS THE END"
+
+arrayStream = function(arr) {
+ var position = 0
+ return {
+ next: function() {
+ if (position == arr.length) {
+ return EOF
+ } else {
+ var result = arr[position]
+ position += 1
+ return result
+ }
+ }
+ }
+}
View
3 spec/stream/suite.js
@@ -0,0 +1,3 @@
+require("./spec_helper")
+
+jasmine.requireAllSpecFiles(__dirname)

0 comments on commit 9a62968

Please sign in to comment.
Something went wrong with that request. Please try again.