Skip to content

Commit

Permalink
Add apply()
Browse files Browse the repository at this point in the history
  • Loading branch information
erayd committed Jan 5, 2020
1 parent c75e22f commit 3ed868e
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,18 @@ if (s.isFull()) {
```
Check whether the queue is currently empty.

### .apply(transform, [reverse = false, [...constructorParams]])
Apply a transform function to all items traversing the queue, and return another
queue containing the results.

By default, items will be removed from the start of the queue (`dequeue()`) and
added to the end of the result queue (`enqueue()`). However, if `reverse` is true,
then items will be removed using `pop()` and added to the result queue using
`unshift()`.

Any remaining parameters will be passed directly to the constructor for the result
queue.

### Properties
#### .length
The number of items currently stored in the queue.
Expand Down
26 changes: 26 additions & 0 deletions spique.js
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,32 @@ module.exports = class Spique extends events.EventEmitter {
return firstRing.peekStart();
};

// apply a transform function and return a new queue of transformed items
this.apply = function(transform, reverse = false, ...createParams) {
let dest = new Spique(...createParams);
let close = false;
this.on("close", () => close = true);

dest.on("space", dest => {
while (!dest.isFull() && !this.isEmpty()) {
if (reverse) {
dest.unshift(transform(this.pop()));
} else {
dest.enqueue(transform(this.dequeue()));
}
}
if (!dest.isFull()) {
if (close) {
dest.close();
} else {
this.once("ready", src => dest.emit("space", dest));
}
}
});

return dest;
}

// iterator dequeue
this[Symbol.iterator] = function*() {
while(!this.isEmpty())
Expand Down

0 comments on commit 3ed868e

Please sign in to comment.