定义与ES6映射一起使用的自定义hash()方法 [英] Define a custom hash() method for use with ES6 maps

查看:74
本文介绍了定义与ES6映射一起使用的自定义hash()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了说明问题,请考虑以下简单对象

To illustrate the problem, consider the following simple object

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

现在我创建一个ES6 地图实例,并且像这样一个条目进入

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' );



c>不是地图的一部分

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.

我现在要做的是添加一些类似于 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.

推荐答案


p>

Is something like this possible?

不,这是ES6 Collections的已知缺陷。他们所做的只是检查参考标识,没有办法改变。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆