Skip to content

Instantly share code, notes, and snippets.

@algesten
Last active September 18, 2015 18:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save algesten/2a4b6e37a2d764f5672e to your computer and use it in GitHub Desktop.
Save algesten/2a4b6e37a2d764f5672e to your computer and use it in GitHub Desktop.
plift and ppipe example

Implemented in https://github.com/algesten/fnuc/blob/master/src/fnuc.coffee#L202

Case for plift

This example shows how plift can help to treat functions dealing with promises as regular functions.

N.B. This code is a "handler" it is not intended to be side effect free.

  • userToDevices is a function looking up devices from a user id in a database. It returns a promise for the result.
  • ex.publish publishes the result over AMQP. Our wrapper makes this also return a promise.

However, when writing the test code for these functions, we can simply ignore that there are any promises involved. Both ex and userToDevices can be mocked to return immediate function returns and we can still be confident it works for promises.

{firstfn, map, mixin, plift, sequence} = require 'fnuc'
Q = require 'q'

ppipe = (fs...) -> sequence (map(plift) fs)...  # sequence of plifted funcs

# mixin the message into the device specification
deviceWithMessage = (message) -> (d) -> mixin d, {message}

# check if given array has any promise
anyPromise = firstfn Q.isPromiseAlike

# wait for all promises in array to resolve or just return array
waitFor = (todo) -> if anyPromise(todo) then Q.all(todo) else todo

# {user:<userid>, message:{title:<title>, body:<body>}}
module.exports = (ex, userToDevices) ->

    # publish the message to exchange
    publish = (m) -> ex.publish 'device', m

    (user, message) ->
        ppipe(
            userToDevices,
            map(deviceWithMessage(message)),
            map(publish),
            waitFor
        ) user
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment