Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

user defined object equality for a set in harmony (es6)

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?

like image 370
Mike McFarland Avatar asked Nov 23 '14 21:11

Mike McFarland


1 Answers

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.
like image 145
Felix Kling Avatar answered Nov 13 '22 17:11

Felix Kling