Skip to content

Instantly share code, notes, and snippets.

@lulalachen
Created May 3, 2018 17:22
Show Gist options
  • Save lulalachen/89619af77df0f5a90565de0d2469aef4 to your computer and use it in GitHub Desktop.
Save lulalachen/89619af77df0f5a90565de0d2469aef4 to your computer and use it in GitHub Desktop.
const curry = require('ramda').curry // or other library
// Section 1
const add = (a, b) => a + b
add(1, 2) // 3
add(1) // NaN
const add_curried = curry(add)
add(1, 2) // 3
add(1)(2) // 3
add(1) // b => 1 + b
// Section 2
const users = [
{ id: 1, name: 'lulala', posts: [{ title: 'test1' }, { title: 'test111' }] },
{ id: 2, name: 'poka', posts: [{ title: 'test2' }, { title: 'test222' }] },
{ id: 3, name: 'cookie', posts: [{ title: 'test3' }, { title: 'test333' }] },
]
// Goal: get user ids and names
// Approach 1
const getIDs = object => objects.map(object => object.id)
const getNames = object => objects.map(object => object.name)
getIDs(users) // [1, 2, 3]
// Approach 2
const get = curry((key, object) => object[key])
// equivilant to: const get = key => object => object[key]
const map = curry((fn, value) => value.map(fn))
const getIDs = map(get('id'))
const getNames = map(get('name'))
getIDs(users) // [1, 2, 3]
getNames(users) // ['lulala', 'poka', 'cookie']
// Goal: get all post titles
// Approach 1
getUserDataFromAPI()
.then(users => users.map(user => user.posts))
.then(posts => posts.map(post => post.title))
// Approach 2
getUserDataFromAPI()
.then(map(get('posts')))
.then(map(get('title')))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment