定义用于 ES6 映射的自定义 hash() 方法 [英] 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;
}
现在我创建一个 ES6 Map
实例并像这样向其中输入一个条目
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
到目前为止一切都很好.然而,如果我像这样创建一个几乎相同的对象 key2
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' );
所以基本上两个键是相同的,但显然 key2
不是映射的一部分
So basically both keys are identical, but obviously key2
is not part of the map
console.log( 'key2: ', map.has( key2 ) );
// key2: false
JavaScript 在这里使用对象引用作为键,因此两个单独的对象不会指向相同的值.
JavaScript uses the object references as a key here, so the two separate objects will not point towards the same value.
我现在想要做的是,向键的 prototype
添加类似 hash()
方法的东西,以便两个对象都指向同样的钥匙.这样的事情可能吗?
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?
我知道,有一种方法可以使用工厂模式来生成 Key
和一些缓存来规避这个问题.然而,这会导致很多关于对象不变性和缓存阻止旧对象被垃圾收集的问题.所以我认为这不是一个真正的选择.
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.
推荐答案
这样的事情有可能吗?
Is something like this possible?
不,这是 ES6 集合的一个已知缺陷.他们所做的只是检查参考身份,而且没有办法改变这一点.
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.
您能做的最好的事情(如果像您所说的那样对实例进行哈希处理不是一种选择)就是不要使用对象作为键.相反,使用对 Key
值进行编码的字符串,并在两种表示之间来回转换.鉴于您认为您的密钥是不可变的,这应该不会造成问题.
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.
这篇关于定义用于 ES6 映射的自定义 hash() 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!