Skip to content

Instantly share code, notes, and snippets.

@onurkerimov
Last active November 17, 2025 18:18
Show Gist options
  • Select an option

  • Save onurkerimov/cfb53af7fd31f01001a3ca5a219a9155 to your computer and use it in GitHub Desktop.

Select an option

Save onurkerimov/cfb53af7fd31f01001a3ca5a219a9155 to your computer and use it in GitHub Desktop.
// --- beauty begins ---
const createLens = (get, set) => ({ get, set });
const view = (obj, lens) => lens.get(obj)
const compose = (lenses) => {
return createLens(
(obj) => lenses.reduce(view, obj),
(value, obj) =>
lenses.reduceRight((acc, lens, index) =>
lens.set(acc, lenses.slice(0, index).reduce(view, obj)), value)
);
};
// --- bureaucracy begins ---
const shallowCopy = (obj) =>
Array.isArray(obj)
? obj.slice()
: Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj))
const prop = (key) => createLens(
(obj) => obj[key],
(value, obj) => {
const nextObj = shallowCopy(obj)
nextObj[key] = value
return nextObj
}
);
// --- craziness begins ---
const SELECTOR_RESULT = Symbol()
const selectorProxyHandler = {
get: (path, key) => {
if (key === SELECTOR_RESULT) return path
return new Proxy([...path, key], selectorProxyHandler)
},
}
const selectorProxy = new Proxy([], selectorProxyHandler)
// --- destiny begins ---
const withSelector = (fn, selector) => {
let prev = Symbol()
return (value) => {
const next = selector(value)
if(next !== prev) {
fn(next)
prev = next
}
}
}
const atomMap = new WeakMap()
const getAtomFromCache = (atom, path) => {
// ...
}
const focusAtom = <T, U>(atom: Atom<T>, selector: PropertyKey[] | PropertyKey | ((s: T) => U)) => {
const path = typeof selector === 'function'
? selector(selectorProxy)[SELECTOR_RESULT]
: typeof selector === 'string'
? [selector]
: selector
// const maybeCachedAtom = getFocusAtomFromCache(atom, path)
// if(maybeCachedAtom) return maybeCachedAtom
const lens = compose(path.map(prop))
return {
get: () => selector(atom.get()),
set: (value) => atom.set(lens.set(value, atom.get())),
subscribe: (fn) => atom.subscribe(withSelector(fn, selector))
}
}
// --- usage ---
const atom = atom({ deeply: { nested: ['hello', 'world'] } })
const nestedAtom = focusAtom(atom, (s) => s.deeply.nested[1])
console.log('nestedAtom.get()', nestedAtom.get())
nestedAtom.set('dunya')
console.log('nestedAtom.set("dunya")', atom.get())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment