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

孤街醉人 提交于 2019-11-26 11:30:41

问题


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?


回答1:


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.



回答2:


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.



来源:https://stackoverflow.com/questions/27094680/user-defined-object-equality-for-a-set-in-harmony-es6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!