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?
This will do it for constructors like what you're working with.
Some other types of objects you might need something different, but this should be ok for what you need.
The above is what you need in function form. To get it to work with
Set
you will have to inherit theSet
object, and override thehas
method with your ownhas
.No not really. There has been some discussion about this on the mailing list. The result is: