Skip to content

Instantly share code, notes, and snippets.

@mofas
Last active May 9, 2018 06:16
Show Gist options
  • Save mofas/7cdc6e8532a3dcde4f67ffca15e0adc2 to your computer and use it in GitHub Desktop.
Save mofas/7cdc6e8532a3dcde4f67ffca15e0adc2 to your computer and use it in GitHub Desktop.
Build map in function closure
// At first, we need to build empty map.
// Empty map is just a function, it will return undefined when invoked.
// When you set new key-value into map, it will wrap a new function around previous map,
// and when you get something from map with key, it will pass key to every nested function until it match or hit empty map.
const map = () => undefined;
const set = map => (key, value) => q => q === key ? value: map;
const get = map => key => typeof map === 'function' ? get(map(key))(key) : map;
// Demo time!
const map1 = set(map)('key1', 1);
get(map1)('key1') // 1
get(map1)('key2') // undefiend
const map2 = set(map1)('key2', 2)
get(map2)('key1') // 1
get(map2)('key2') // 2
const map3 = set(map2)('key1', 3)
get(map3)('key1') // 3
get(map3)('key2') // 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment