Respuesta :

Step-by-step explanation:

ES6 has a new Set data structure for storing sets of unique objects. However it is based on object references as opposed to value comparisons. As far as I can tell this makes it impossible to have a set of pairs of numbers without stringifying.

For example, typing in Chrome's console (needs Chrome 38+):

> var s = new Set(); < undefined > s.add([2, 3]); < Set {[2, 3]} > s.has([2, 3]) < false <--- was hoping for 'true'

This appears to be by design: since I passed a different array of [2, 3] to has(), it returns false, because although the contents is the same it only looks at object references, and I allocated a new and different array to pass to has(). I would need to store a reference to the original array I passed to add() to check with has(), but this is not always possible. For example if the number pairs represent co-ordinates, I might need to check if the set has [obj.x, obj.y], but this will always return false since it allocates a new array.

The workaround is to stringify the arrays and key on strings like "2, 3" instead. However in something performance-sensitive like a game engine, it is unfortunate if every set access needs to make a string allocation and convert and concatenate number strings.

Does ES6 provide any feature to solve this problem without stringifying, or is there any feature on the horizon with ES7 that could help as well?

javascriptperformancedata-structuressetecmascript-6

Share

2

Follow

asked Sep 21 '14 at 13:06

AshleysBrain

20.4k1515 gold badges8181 silver badges119119 bronze badges

Add a comment

3 Answers

ActiveOldestVotes

3

As you've noted [2, 3] === [2, 3] is false, meaning you can't use Set like this; however, is Set really the best option for you?

You may find that using a two-level data structure like this will be better for you

var o = {}; function add(o, x, y) { if (!o[x]) o[x] = {}; o[x][y] = true; } function has(o, x, y) { return !!(o[x] && o[x][y]); } function del(o, x, y) { if (!o[x]) return; delete o[x][y]; // maybe delete `o[x]` if keys.length === 0