和谐集合的用户定义对象相等性 (es6) [英] user defined object equality for a set in harmony (es6)
问题描述
我有一个问题,我生成了许多值,需要确保我只使用唯一的值.由于我使用的是带有 --harmony 标志的节点 js,并且可以访问和声集合,因此我决定 Set 可能是一个选项.
I have a problem where I'm generating many values and need to make sure I only work with unique ones. Since I'm using node js, with the --harmony flag, and have access to harmony collections, I decided that a Set may be an option.
我正在寻找类似于以下示例的内容:
What I'm looking for is something similar to the following example:
'use strict';
function Piece(x,y){
this.x = x
this.y = y
}
function Board(width,height,pieces){
this.width = width
this.height = height
this.pieces = pieces
}
function generatePieces(){
return [
new Piece(0,0),
new Piece(1,1)
]
}
//boardA and boardB are two different but equivalent boards
var boardA = new Board(10,10,generatePieces())
var boardB = new Board(10,10,generatePieces())
var boards = new Set()
boards.add(boardA)
boards.has(boardB) //return true
现在通常要在另一种语言中实现这一点,比如 c#,我希望必须实现一个 equals 函数,以及一个用于 Board 和 Piece 的哈希代码生成函数.因为我希望默认对象相等性基于引用.或者可能使用特殊的不可变值类型(例如,Scala 中的 case 类)
Now normally to achieve this in another language, say c#, I would expect to have to implement an equals function, as well as a hash code generating function for both Board and Piece. Since I'd expect the default object equality to be based on references. Or perhaps use a special immutable value type (say, a case class in scala)
有没有办法为我的对象定义相等性来解决我的问题?
Is there a means to define equality for my objects to solve my problem?
推荐答案
有没有办法为我的对象定义相等性来解决我的问题?
Is there a means to define equality for my objects to solve my problem?
不,不是.在邮件列表中已经对此进行了一些讨论.结果是:
No not really. There has been some discussion about this on the mailing list. The result is:
- 在 Set/Map 之上构建您自己的 Set/Map 抽象,这将根据您的散列函数将对象转换为原始值.
- 等待 ES7 中的值对象.
这篇关于和谐集合的用户定义对象相等性 (es6)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!