Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

javascript - Define a custom hash() method for use with ES6 maps

To illustrate the problem, consider the following simple object

function Key( val ) {
  this._val = val;
}

Now I create a ES6 Map instance and feed one entry into it like this

var map = new Map(),
    key1 = new Key( 'key' );

map.set( key1, 'some value' );

console.log( 'key1: ', map.has( key1 ) );
// key1:  true

So far everything is fine. The challenge, however, comes up, if I create a nearly identical object key2 like this

var key2 = new Key( 'key' );

So basically both keys are identical, but obviously key2 is not part of the map

console.log( 'key2: ', map.has( key2 ) );
// key2:  false

JavaScript uses the object references as a key here, so the two separate objects will not point towards the same value.

What I would like to do now is, to add something like a hash() method to key's prototype, so that both object would point to the same key. Is something like this possible?


I know, that there would be a way to circumvent the problem using a factory pattern for the Key generation together with some caching. However, this results in a lot of problem regarding immutability of the objects and the cache preventing old objects from being garbage collected. So I think that is not really an option.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Is something like this possible?

No, this is a known flaw of ES6 Collections. All they do is check for reference identity, and there is no way to change that.

The best thing you can do (if hash consing the instances is not an option as you say) is not to use objects for the keys. Instead, use strings that encode the Key values, and convert back and forth between the two representations. Given that you consider your keys to be immutable, this should not pose a problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...