Created
September 20, 2017 20:21
-
-
Save harmenjanssen/df42254585deedb5bcb6948a7db03ab8 to your computer and use it in GitHub Desktop.
Struggling with "carrying over" arguments in a function composition. In the example I would like the final `assoc` call in the composition to end up knowing about both the page's URL property and the menuItem object.
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
import { pages, menuItems } from "./data.js"; | |
import { propEquals, prop, assoc, compose, map } from "./util.js"; | |
const findPageById = id => pages.find(propEquals("id", id)); | |
// Put a "url" property on the menuItems, taken from the related Page | |
console.log( | |
map( | |
compose( | |
assoc( | |
"url", | |
/* how to get the value of Page.url here? */, | |
/* how to get a ref to the menuItem here? */ | |
), | |
prop("url"), | |
findPageById, | |
prop("page_id") | |
), | |
menuItems | |
) | |
); |
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
// ======================== | |
// Data | |
// ======================== | |
export const pages = [ | |
{ id: 1, title: "Foo", url: "/foo" }, | |
{ id: 2, title: "Bar", url: "/bar" }, | |
{ id: 3, title: "Baz", url: "/baz" } | |
]; | |
export const menuItems = [ | |
{ title: "Menu item 1", page_id: 2 }, | |
{ title: "Menu item 2", page_id: 3 }, | |
{ title: "Menu item 3", page_id: 1 } | |
]; |
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
// ======================== | |
// util | |
// ======================== | |
export const curry = fn => { | |
const arity = fn.length; | |
return (...args) => args.length < arity ? curry(fn.bind(null, ...args)) : fn(...args); | |
}; | |
export const compose = (...fns) => x => fns.reduceRight((acc, cur) => cur(acc), x); | |
export const prop = curry((x, o) => o[x]); | |
export const propEquals = curry((x, v, o) => o[x] === v); | |
export const assoc = curry((x, v, o) => Object.assign(o, { [x]: v })); | |
export const map = curry((f, xs) => xs.map(f)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment