Skip to content

Instantly share code, notes, and snippets.

@aleclarson
Created July 19, 2019 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aleclarson/b3341fe5cac0f5a94144c5216eec0851 to your computer and use it in GitHub Desktop.
Save aleclarson/b3341fe5cac0f5a94144c5216eec0851 to your computer and use it in GitHub Desktop.
export interface Lens<T> {
(): T
(newValue: T): void
}
export function bind<T>(get: () => T, set: (newValue: T) => void): Lens<T>
export function bind<T, U>(target: Map<T, U>, key: T): Lens<U>
export function bind<T extends object, P extends keyof T>(
target: T,
key: P
): Lens<T[P]>
export function bind(get: any, set: any) {
if (typeof get !== 'function') {
const obj = get
const key = set
if (get instanceof Map) {
get = () => obj.get(key)
set = (value: any) => obj.set(key, value)
} else {
get = () => obj[key]
set = (value: any) => (obj[key] = value)
}
}
return function(value?: any) {
return arguments.length ? void set(value) : get()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment