user defined object equality for a set in harmony

2019-01-07 23:35发布

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?

2条回答
爷的心禁止访问
2楼-- · 2019-01-08 00:23

This will do it for constructors like what you're working with.

var sameInstance = function(obj1, obj2){
    return obj2 instanceof ob1.constructor;
};

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 the Set object, and override the has method with your own has.

查看更多
放我归山
3楼-- · 2019-01-08 00:28

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.
查看更多
登录 后发表回答