Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set of Tuples in JavaScript?

What is the best way to implement a Set of coordinates in JavaScript? I would like to be able to do things like:

let s=new Set();
s.add([1,1]);
if (s.has([1,1])) // false, since these are different arrays

The above doesn't work, since the Set is storing a reference to the array instead of the contents.

like image 529
DavidXYZ Avatar asked Jul 30 '20 19:07

DavidXYZ


2 Answers

You can subclass Set for more flexibility.

class ObjectSet extends Set{
  add(elem){
    return super.add(typeof elem === 'object' ? JSON.stringify(elem) : elem);
  }
  has(elem){
    return super.has(typeof elem === 'object' ? JSON.stringify(elem) : elem);
  }
}
let s=new ObjectSet();
s.add([1,1]);
console.log(s.has([1,1]))
console.log(s.has([1,2,3]));
console.log([...s]);
console.log([...s].map(JSON.parse));//get objects back
like image 88
Unmitigated Avatar answered Sep 26 '22 17:09

Unmitigated


This can be done with strings:

let s=new Set();
s.add("1,1");
s.add("2,2");
console.log(s.has("1,1"), s.has("1,2")); // true false

However, I would prefer to do this with some type of numeric tuple to avoid repeated string conversion logic.

like image 24
DavidXYZ Avatar answered Sep 25 '22 17:09

DavidXYZ