Created
February 8, 2017 16:42
-
-
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 …
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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