Last active
March 8, 2017 17:49
-
-
Save itrelease/d7d54a6bd3aabc70ef1daf07b7f7bb88 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
const bigBird = { | |
name: 'Big Bird', | |
address: { name: 'Whatever' }, | |
age:6, | |
comments:[ | |
{body:'sing, sing a song',title:'Line 1'}, | |
{body:'make it simple',title:'Line 2'}, | |
{body:'sing out strong',title:'Line 3'}] | |
}; | |
const pipe = (fn,...fns) => (...args) => fns.reduce( (acc, f) => f(acc), fn(...args)); | |
const compose = (...fns) => pipe(...fns.reverse()); | |
const curry = (f, ...args) => (f.length <= args.length) ? | |
f(...args) : | |
(...more) => curry(f, ...args, ...more); | |
const update = R.update; //for Arrays | |
const assoc = R.assoc; //for Objects | |
const fmap = curry((f, mappable) => mappable.map(f)); | |
const arrayLens = curry( | |
(index, f, xs) => fmap(replacement => update(index, replacement, xs), f(xs[index])) | |
); | |
const objectLens = curry( | |
(key, f, xs) => { | |
return fmap(replacement => assoc(key, replacement, xs), f(xs[key])) | |
} | |
); | |
const _K = x => (_) => x; | |
const Const = x => ({value: x, map(){ return this; }}); | |
const Identity = x => ({value: x, map: mapf => Identity(mapf(x)) }); | |
const Maybe = x => ({ value: x, map: function (mapf) { return x ? Maybe(mapf(x)) : this; } }); | |
const view = curry( (lens, targetData) => lens(Const)(targetData).value ); | |
const over = curry( (lens, apf, targetData) => lens(y => Identity(apf(y)))(targetData).value ); | |
const set = curry( (lens, val, targetData) => over(lens, _K(val), targetData) ); | |
// console.log(over(objectLens('name'), (v) => v.toUpperCase(), bigBird)); | |
// console.log(view(compose(objectLens('comments'), arrayLens(0)), bigBird)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment