Skip to content

Instantly share code, notes, and snippets.

@mediaupstream
Last active March 21, 2018 21:51
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 mediaupstream/4aae7ff28cf945aab6e8b5c103268633 to your computer and use it in GitHub Desktop.
Save mediaupstream/4aae7ff28cf945aab6e8b5c103268633 to your computer and use it in GitHub Desktop.

Composable middleware

Ever wanted to run some validation functions before another function is called? Use composable middleware, it's fun!

// compose fns together
const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)))
// If `fn` evaluates to true call fn2 passing args through
const middleware = fn => fn2 => (...args) => fn(...args) && fn2(...args)
//
// Example usage and tests
//
// create a middleware to ensure exactly two Args are passed to the function
const hasTwoArgs = middleware((...Args) => Args.length === 2)
// create a middleware to ensure that the first arg is an array
const firstArgIsArray = middleware(a => Array.isArray(a))
// compose the middleware together
const hasTwoFirstArray = compose(hasTwoArgs, firstArgIsArray)
// This function will only execute if there are exactly two args and the
// first arg is an array
const myValidatedFn = hasTwoFirstArray((a, b) => `It worked ${a} ${b}`)
// feature rich assertion library
const expect = t => ({ toEqual: v => v === t
? `\u2714 Passed`
: `\u274C Failed. Expected "${t}" to equal "${v}"`
})
// tests
expect(myValidatedFn([1,2,3], 'something')).toEqual('It worked 1,2,3 something')
expect(myValidatedFn([1,2,3], 'something', 'bad')).toEqual(false)
expect(myValidatedFn('bad', 'something')).toEqual(false)
expect(myValidatedFn()).toEqual(false)
expect(myValidatedFn('bad')).toEqual(false)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment