Created
July 19, 2019 01:28
-
-
Save aleclarson/b3341fe5cac0f5a94144c5216eec0851 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
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