Skip to content

Instantly share code, notes, and snippets.

@maetl
Created March 25, 2017 12:09
Show Gist options
  • Select an option

  • Save maetl/2d973084e703530d9ef18d3f0e5a153f to your computer and use it in GitHub Desktop.

Select an option

Save maetl/2d973084e703530d9ef18d3f0e5a153f to your computer and use it in GitHub Desktop.

Revisions

  1. maetl created this gist Mar 25, 2017.
    64 changes: 64 additions & 0 deletions pipe.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,64 @@
    function Pipe(sequence) {
    const wrappedIterator = sequence[Symbol.iterator]();
    this.next = wrappedIterator.next.bind(wrappedIterator);
    }

    Pipe.step = function(generator) {
    return new Pipe({
    [Symbol.iterator]: generator
    });
    }

    Pipe.prototype[Symbol.iterator] = function() {
    return this;
    }

    Pipe.prototype.map = function(fn) {
    const sequence = this;

    return Pipe.step(function*() {
    for (let entry of sequence) {
    yield fn(entry);
    }
    });
    }

    Pipe.prototype.filter = function(fn) {
    const sequence = this;

    return Pipe.step(function*() {
    for (let entry of sequence) {
    if (fn(entry)) yield entry;
    }
    });
    }

    Pipe.prototype.take = function(number) {
    const sequence = this;

    return Pipe.step(function*() {
    for (let index=0; index < number; index++) {
    yield sequence.next().value;
    }
    })
    }

    Pipe.prototype.all = function() {
    return [...this];
    }

    const evenValues = (x) => (x % 2) == 0;
    const squareValues = (x) => x * 2;

    const filteredPipeline = new Pipe([1,2,3,4]).filter(evenValues);

    console.log("expected: 2", `actual: ${filteredPipeline.next().value}`);
    console.log("expected: 4", `actual: ${filteredPipeline.next().value}`);

    const squareEvenValues = new Pipe([1,2,3,4,5,6,7,8,9]).filter(evenValues).map(squareValues);

    console.log("expected: 4,8,12,16", `actual: ${squareEvenValues.all()}`);

    const firstTwoSquared = new Pipe([1,2,3,4,5,6]).filter(evenValues).map(squareValues).take(2);

    console.log("expected: 4,8", `actual: ${firstTwoSquared.all()}`);