Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A basic implementation of a multi-field map, where each mapping consists of a number of keyed properties, and a record may be retrieved based on any one of those fields. Works well for scenarios where you would reach for a Map, but want to be able to retrieve a key from its corresponding value; also multi-dimensional mappings, where you want to …
function multiMap( keys ){
const lists = {}
keys.forEach( key => lists[ key ] = [] )
return {
set( entry ){
let index = lists[ keys[ 0 ] ].indexOf( entry[ keys[ 0 ] ] )
if( index < 0 ) index = lists[ key[ 0 ] ].length
keys.map( key => lists[ key ][ index ] = entry[ key ] )
}
get( key, value ){
const record = Object.create( null )
const index = lists[ key ].getIndexOf( value )
keys.forEach( key => record[ key ] = list[ key ][ index ] )
return record
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment