oop - When creating a set (unique elements of same type) in JavaScript, what is customary to use as values for a key? -
since javascript has no straight concept of "set", way create object acts set create associative array keys elements of set , values true
, e.g.
function toset ( arr ) { // return set of var s = {}; arr.foreach(function (elem) { s[elem] = true; }); return s; }
since true
s dummy data, there better value use? maybe 1 takes 1 byte?
since javascript has no straight concept of "set"...
javascript have set
object of es6. can read here on mdn. and, there multiple polyfills use similar in pre-es6 environments.
if trying simulate set
using plain javascript object, key must string have find unique representation of object can used string key. number, that's string representation of number, boolean, that's "true"
or "false"
. object, have create unique string represents object , if object presented again can recreate same string. there multiple possibilities how in pre-es6. es6 set can hold object directly without making string representation of it.
here's related answer on using set-like object in pre-es6: mimicking sets in javascript?
and, derivative of that aims more es6 set interface here: https://github.com/jfriend00/es6-set.
in es6-like interface, there's function called getkey()
here illustrates strategy making unique string key many types of es5 variables. can see details there.
as set data in set, best bet set actual value of data in set because key forced string need store actual value somewhere. so, if value isn't string itself, actual value can value in object.
since trues dummy data, there better value use? maybe 1 takes 1 byte?
as data size, how javascript variables stored implementation detail not forced specification can vary 1 implementation another. because variable's type has part of value, every variable has have sort of universal part of value. you're not find value smaller simple boolean since type has 2 possible values should small possible already.
but, if want able tell difference between 3
, "3"
stored in set (e.g. want them stored separate items in set), have add type modifier key stored separate keys , if want able values set need able reconstruct original value. 1 simple way original value store value of property on object rather true
.
Comments
Post a Comment