1

I ended creating a structure that given a hashmap allows you to search the value that corresponds to certain key and the key that corresponds to certain value. But I don't know if such construction has a name or is part of any design principle/pattern

Here is an example implementation:

import { fromArrays } from './objectUtils';

export default class Dict {
    constructor(obj) {
        this.map = obj;
        this._keys = Object.keys(obj);
        this._values = Object.values(obj)
        this.reversed = fromArrays(this._values, this._keys)
    }

    getKeyFor(value) {
        return this.reversed[value]
    }

    getValue(key) {
        return this.map[key]
    }

    hasValue(value) {
        return this.reversed.hasOwnProperty(value)
    }

    get keys() {
        return this._keys
    }

    get values() {
        return this._values
    }

    get object() {
        return this.map
    }
}

I called it Dict, but to be honest I have no idea how to call it. As you can see, you have to provide an object that will be encapsulated. The implementation is not very nice and there are situations where it will not work properly, for example for non-unique values, but in my current use-case this should not happen, so it's not a problem for me.

But, if there is documentation about this type of construct I would like to learn about it. I tried googling about the features, but internet is bloated of questions and tutorials about how to map and object or how to find inside an array.

Thanks in advance.

Danielo515
  • 5,996
  • 4
  • 32
  • 66
  • Though it' in java, see https://stackoverflow.com/questions/3430170/how-to-create-a-2-way-map-in-java – dev8080 Sep 27 '17 at 10:45

1 Answers1

0

Though there is no native structure like this in Javascript, you may want to check out this implementation of a BiMap. I think it will give you what you're looking for.

For installation in a Node package, use npm install bimap, then include bimap.js in your code; from there, you can create new BiMaps using new BiMap.

Dykotomee
  • 728
  • 6
  • 20
  • 1
    So the answer is that the structure is called BiMap. Thanks for pointing to a JS implementation by the way – Danielo515 Sep 27 '17 at 14:46