Skip to content

Instantly share code, notes, and snippets.

@leihuang23
Created January 18, 2019 00:08
Show Gist options
  • Save leihuang23/28003cdd19d2486efe10fd5caa58a9a1 to your computer and use it in GitHub Desktop.
Save leihuang23/28003cdd19d2486efe10fd5caa58a9a1 to your computer and use it in GitHub Desktop.
Lens implementation in JavaScript
const curry = fn => (...args) =>
args.length >= fn.length ? fn(...args) : curry(fn.bind(undefined, ...args))
const always = a => b => a
const compose = (...fns) => args => fns.reduceRight((x, f) => f(x), args)
const getFunctor = x =>
Object.freeze({
value: x,
map: f => getFunctor(x),
})
const setFunctor = x =>
Object.freeze({
value: x,
map: f => setFunctor(f(x)),
})
const prop = curry((k, obj) => (obj ? obj[k] : undefined))
const assoc = curry((k, v, obj) => ({ ...obj, [k]: v }))
const lens = curry((getter, setter) => F => target =>
F(getter(target)).map(focus => setter(focus, target))
)
const lensProp = k => lens(prop(k), assoc(k))
const lensPath = path => compose(...path.map(lensProp))
const view = curry((lens, obj) => lens(getFunctor)(obj).value)
const over = curry((lens, f, obj) => lens(y => setFunctor(f(y)))(obj).value)
const set = curry((lens, val, obj) => over(lens, always(val), obj))
@mk0y
Copy link

mk0y commented Jun 9, 2020

This is the only custom lenses implementation that actually works. So thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment