一组和谐的用户定义的对象相等(es6) [英] user defined object equality for a set in harmony (es6)
问题描述
由于我使用节点js,使用--harmony标志,并且可以访问和声集合,所以我决定Set可以是一个选项。
我正在寻找的是类似于以下示例:
'use strict';
function Piece(x,y){
this.x = x
this.y = y
}
function Board(宽度,高度,片段){
this.width = width
this.height = height
this.pieces = pieces
}
function generatePieces ){
return [
new Piece(0,0),
new Piece(1,1)
]
}
/ / boardA和boardB是两个不同但相当的板
var boardA =新板(10,10,generatePieces())
var boardB =新板(10,10,generatePieces())
var boards = new Set()
boards.add(boardA)
boards.has(boardB)// return true
现在通常用另一种语言来实现这一点,比如说c#,我希望实现一个equals函数,以及一个用于板和块的哈希码生成函数。因为我希望默认的对象相等是基于引用。
或者可能使用一个特殊的不可变价值类型(例如,Scala中的一个案例类)
有没有办法定义我的对象的等同性来解决我的问题?
有没有办法为我的对象定义平等来解决我的问题? p>
没有没有。在邮件列表上已经有关于此的一些讨论。结果是:
- 在Set / Map之上构建您自己的Set / Map抽象,它会将对象转换为基本值到你的散列函数。
- 等待 ES7中的值对象。
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
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:
- Build your own Set/Map abstraction on top of Set/Map, which would convert the objects to a primitive value according to your hashing function.
- Wait for value objects coming in ES7.
这篇关于一组和谐的用户定义的对象相等(es6)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!