Skip to content

Instantly share code, notes, and snippets.

@barneycarroll
Created February 8, 2017 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barneycarroll/ccbadedd2b64ced4dd6c8b62931d4ef9 to your computer and use it in GitHub Desktop.
Save barneycarroll/ccbadedd2b64ced4dd6c8b62931d4ef9 to your computer and use it in GitHub Desktop.
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