Ever wanted to run some validation functions before another function is called? Use composable middleware, it's fun!
Last active
March 21, 2018 21:51
-
-
Save mediaupstream/4aae7ff28cf945aab6e8b5c103268633 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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