JavaScript implementation of Python collections.defaultdict
Switch branches/tags
Nothing to show
Clone or download
Pull request Compare This branch is 17 commits ahead of jdubie:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
test
.gitignore
DefaultMap.ipynb
LICENSE
Makefile
README.md
index.js
package.json

README.md

DefaultMap

DefaultMap - JavaScript implementation of Python collections.defaultdict

Implementation

const DefaultMap = (defaultValue = undefined) => {
    const map = new Map()
    const set = (key, value) => {map.set(key, value)}
    const get = key => map.get(key) || defaultValue 
    return {set, get}
}

export default DefaultMap

Examples

const myDefaultMap = DefaultMap(0)
myDefaultMap.get('abc') // 0
myDefaultMap.set('abc', 45)
myDefaultMap.get('abc') // 45
const myDefaultMap2d = DefaultMap(DefaultMap(0))
myDefaultMap2d.get('a').get('b') // 0
myDefaultMap2d.get('a').set('b', 42)
myDefaultMap2d.get('a').get('b') // 42