Last active
March 21, 2018 17:56
-
-
Save mediaupstream/5335310d3d8bedc79e60f2a1621644c3 to your computer and use it in GitHub Desktop.
This file contains 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
// It's composable | |
const compose = (a,b) => v => a(b(v)) | |
const isValid = valid => fn => (...p) => valid(...p) && fn(...p) | |
const hasTwoParams = isValid((...params) => params.length === 2) | |
const firstParamIsArray = isValid(a => Array.isArray(a)) | |
const hasTwoFirstArray = compose(hasTwoParams, firstParamIsArray) | |
const myValidatedFn = hasTwoFirstArray((a, b) => console.log('It worked', a, b)) | |
myValidatedFn([1,2,3], 'something') // It worked [ 1, 2, 3 ] something | |
myValidatedFn([1,2,3], 'something', 'bad') // false | |
myValidatedFn('bad', 'something') // false | |
myValidatedFn() // false | |
myValidatedFn('bad') // false |
This file contains 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
// higher order validation creator | |
const isValid = valid => fn => (...p) => valid(...p) && fn(...p) | |
// Example: | |
// Create a specific validation higher order function | |
const hasValidArrayOfObjects = isValid(data => { | |
if (data // is there data | |
&& Array.isArray(data) // is data an array | |
&& data.length // is it not empty | |
&& typeof data[0] == 'object' // does it contain objects | |
&& !Array.isArray(data[0]) // is it a real object (not an array) | |
&& Object.keys(data[0]).length // does it have keys | |
) { | |
return true | |
} | |
// Throw an error | |
throw new Error('Invalid parameter. Expected an Array of objects') | |
}) | |
// Use the validation fn above to create a safe function | |
const safelyExtractKeys = hasValidArrayOfObjects(data => Object.keys(data[0])) | |
// Use the safe function | |
safelyExtractKeys([{name:'smithy', status: 'offline'}]) // ['name', 'status'] | |
safelyExtractKeys() // Throws an Error | |
safelyExtractKeys({}) // Throws an Error | |
safelyExtractKeys([{}]) // Throws an Error | |
safelyExtractKeys(123) // Throws an Error | |
safelyExtractKeys('thing') // Throws an Error | |
safelyExtractKeys([1,2,3]) // Throws an Error | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment