Search code examples
javascriptcoffeescriptchain

javascript function chaining without the chain members knowing about each other


I want to create a javascript pipeline like powershell, bash (|) or f# (|>). Ie. something equivalent to

getstuff() | sort() | grep("foo") | take(5)

I saw a discussion about this in coffeescript forum but in the end they shelved it because everybody said that you could do the same thing with function chaining. But as far as I can see that requires getstuff returns something that has a sort method on it; the sort method must return something that has grep method on it etc. This is pretty restrictive as it requires all potential pipeline members to know about each other in advance. I know JavaScript has some pretty clever tricks in it and I am still at the 101 level - so is this doable

getstuff().sort.().grep().take()

without that constraint


Solution

  • is this doable

    getstuff().sort.().grep().take()
    

    without that constraint

    No.


    I like short answers! Can you suggest any way that something like it could be done

    At a high level, you could do something similar to what jQuery does under the hood to allow chaining. Create an array-like wrapper object type which has all of the functions you want to be able to call; each successive chained call can operate on an internal stack in addition to the explicitly-passed arguments.

    Not to keep beating the dead jQuery horse, but one of the best ways to understand what I'm talking about is to just start digging through the jQuery core source code and figure out how the chaining works.