Last active
December 4, 2019 22:33
-
-
Save jasonrobot/03a84f8501046d8a7694963cb7f3bd94 to your computer and use it in GitHub Desktop.
A little demonstration of Ramda
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
import * as R from 'ramda' | |
// Setting up some date to play with | |
const foo = { | |
validate() { | |
return this.x < 69 && (typeof this.name === 'string'); | |
}, | |
x: 420, | |
name: Symbol('lul') | |
} | |
const bar = { | |
validate() { | |
return this.value > 0 && this.id !== undefined; | |
}, | |
id: 2, | |
value: 42 | |
} | |
const components = [foo, bar] | |
// Old-school approach: use a for loop | |
function withForLoop(){ | |
const result = []; | |
for(let i = 0; i < components.length; i++){ | |
result.push(components[i].validate()); | |
} | |
return result; | |
} | |
//Map is much more concise | |
function withMap(){ | |
return components.map(comp => comp.validate()) | |
} | |
// Using an invoker means no need for the arrow function | |
const validate = R.invoker(0, 'validate'); | |
function withInvoker(){ | |
return components.map(validate) | |
} | |
// Using a partially applied map just gives us a function that validates lists of components. | |
const validateAll = R.map(validate) | |
function withFullRamda(){ | |
return validateAll(components) | |
} | |
// To check if all elements in a list are equal: | |
const allEqual = ([x, ...xs]) => R.all(R.equals(x), xs) | |
allEqual([ | |
withForLoop(), | |
withMap(), | |
withInvoker(), | |
withFullRamda() | |
]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment