Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
*.swp
node_modules/
11 changes: 6 additions & 5 deletions lazy.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,13 @@ function Lazy (em, opts) {
);
}

self.pop = function (f) {
self.head(f);
return self.skip(1);
}

self.head = function (f) {
var lazy = newLazy();
lazy.on(dataName, function g (x) {
f(x)
lazy.removeListener(dataName, g)
})
self.once(dataName, f);
}

self.tail = function () {
Expand Down
1 change: 1 addition & 0 deletions readme.txt
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ Supports the following operations:
* lazy.product(f)
* lazy.foldr(op, i, f)
* lazy.skip(n)
* lazy.pop(f)
* lazy.head(f)
* lazy.tail(f)
* lazy.join(f)
Expand Down
34 changes: 21 additions & 13 deletions test/head.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,33 @@ var assert = require('assert');
var Lazy = require('..');
var expresso = expresso;

function range(i, j) {
var r = [];
for (;i<j;i++) r.push(i);
return r;
}

exports['head'] = function () {
var lazy = new Lazy;
var data = [];
var executed = 0;
lazy.head(function (x) {
assert.equal(x, 0);
executed++;
})
var expect = function(n) {
return function(x) {
executed++;
assert.eql(x, n);
}
}

range(0,10).forEach(function (x) {
// callback should only execute once.
lazy.head(expect(12));
[12, 13, 14].forEach(function (x) {
lazy.emit('data', x);
});
assert.equal(executed, 1);

assert.equal(executed, 1, 'head executed too much');
// multiple calls to head leave the lazy list unchanged.
lazy.head(expect(123));
lazy.head(expect(123));
lazy.head(expect(123));
lazy.join(expect([123, 456, 789]));
[123, 456, 789].forEach(function(x) {
lazy.emit('data', x);
})
assert.equal(executed, 4);
lazy.emit('end');
assert.equal(executed, 5);
}

27 changes: 27 additions & 0 deletions test/pop.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
var assert = require('assert');
var Lazy = require('..');
var expresso = expresso;

exports['pop'] = function () {
var lazy = new Lazy;
var executed = 0;

var expect = function(n) {
return function(x) {
executed++;
assert.eql(x, n);
}
}

lazy.pop(expect(77))
.pop(expect(99))
.join(expect([11, 55, 33]));

[77, 99, 11, 55, 33].forEach(function (x) {
lazy.emit('data', x);
});
lazy.emit('end');

assert.equal(executed, 3);
}