ES2015 - Sets, Maps and Array Questions - javascript

I'm just looking into ES2015, and coming up to Maps, Sets and Arrays.
Question 1
Firstly I'm interested in why they all use a different method to add items to it.
Set.add("item");
Map.set("item");
Array.push("item");
is there method to the madness rather than keeping them all as .push?
Question 2
size vs length.
Why have Map and Set got .size but Array has .length why not use the same?
Question 3
When would you use Map over Array? can anybody give a real world example for this, I understand you can do things like use objects as keys in Maps, but why would you do that in the first place.
Hopefully somebody can clear this up to help inform other new starters to ES2015, thanks.

Sets, Maps and Arrays use different methods, because these methods do different things. Array.prototype.push() adds one or more elements to the end of the array. Set.prototype.add() works similarly, but it only accepts one argument. If it was named push(), some people would think that it works the same as the array method, and they'd try doing set.push(1, 2, 3) and they'd be confused why it adds only the first element.
Map.prototype.set() is a completely different thing. From MDN:
The set() method adds or updates an element with a specified key and value to a Map object.
If an element with a specified key already exists, this method doesn't add any element to the Map, but only updates the value of that element.
You second question was answered on this blog:
length is for sequences, data structures that are indexable – like arrays. size is for collections that are primarily unordered – like maps and sets.
I don't really understand your third question. Maps and Arrays are completely different data structures. Maps are similar to objects, see Maps vs Objects in ES6, When to use?

Related

Hashtable vs objects In javascript

I’m new to data structure and I’m learning it in Javascript.
My Question is:
Why do we need hash tables when we 've objects in javascript?
Can anybody give me a situation where hash tables will be more useful than objects?
"Hashtable" is called different things in different languages. Java has Hashtable and HashMap, Ruby has Hash, Python has dict... in JavaScript, it's called Map.
Objects' keys are limited to strings; Map keys can be anything.
Objects support inheritance; a Map only contains what is specifically put into it.
Think you means Map instead of HashTable. IMHO Map may be more useful and perform better if you need one of that:
keep order of insertions of key/value pairs;
frequent additional and removal;
key which not String/Symbol.
I think you can obtain more information at MDN
The MDN docs on this are quite helpful: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Objects_and_maps_compared
Most notably, using a map gives you the advantage of using anything as a key, maps retain order, and may perform better when constantly adding and removing values.

What is the difference between a dictionary and a Map in Javascript 6? [duplicate]

This question already has answers here:
Map vs Object in JavaScript
(15 answers)
Closed 7 years ago.
How is a Map different from a dictionary/object?
In other words, what is the difference between let x = {} and let x = new Map() ?
Objects and maps compared (from MDN):
Objects are similar to Maps in that both let you set keys to values,
retrieve those values, delete keys, and detect whether something is
stored at a key. Because of this (and because there were no built-in
alternatives), Objects have been used as Maps historically; however,
there are important differences between Objects and Maps that make
using a Map better:
An Object has a prototype, so there are default keys in the map.
This could be bypassed by using map = Object.create(null) since ES5,
but was seldomly done.
The keys of an Object are Strings and Symbols, where they can be
any value for a Map.
You can get the size of a Map easily while you have to manually
keep track of size for an Object.
This does not mean you should use Maps everywhere, objects still are
used in most cases. Map instances are only useful for collections, and
you should consider adapting your code where you have previously used
objects for such. Objects shall be used as records, with fields and
methods. If you're still not sure which one to use, ask yourself the
following questions:
Are keys usually unknown until run time, do you need to look them up dynamically?
Do all values have the same type, and can be used interchangeably?
Do you need keys that aren't strings?
Are key-value pairs often added or removed?
Do you have an arbitrary (easily changing) amount of key-value pairs?
Is the collection iterated?
Those all are signs that you want a Map for a collection. If in
contrast you have a fixed amount of keys, operate on them
individually, and distinguish between their usage, then you want an
object.

When would you use an ES6 Map over an Object? [duplicate]

This question already has answers here:
Map vs Object in JavaScript
(15 answers)
Closed 7 years ago.
I've been looking at the new ES6 docs on MDN and I can't find a real world use for the Map object where a normal object wouldn't work. Does anyone have any use cases for Maps and explain why an object wouldn't work in that scenario?
MDN lists a number of important differences:
An Object has a prototype, so there are default keys in the map. [editor: the good old hasOwnProperty issue]
The keys of an Object are Strings, where they can be any value for a Map.
You can get the size of a Map easily while you have to manually keep track of size for an Object.
A Map iterates its elements in insertion order, whereas iteration order is not specified for Objects.
So a Map is finally an insert-ordered key-value store for Javascript, which additionally allows mapping any value to any value, instead of restricting keys to be strings. This can greatly simplify some code where ordering is important, or where objects or other complex data types need to be associated with other data.

Can I increase lookup speed by positioning properties in object?

I've seen a lot of questions about the fastest way to access object properties (like using . vs []), but can't seem to find whether it's faster to retrieve object properties that are declared higher than others in object literal syntax.
I'm working with an object that could contain up to 40,000 properties, each of which is an Array of length 2. I'm using it as a lookup by value.
I know that maybe 5% of the properties will be the ones I need to retrieve most often. Is either of the following worth doing for increased performance (decreased lookup time)?
Set the most commonly needed properties at the top of the object literal syntax?
If #1 has no effect, should I create two separate objects, one with the most common 5% of properties, search that one first, then if the property isn't found there, then look through the object with all the less-common properties?
Or, is there a better way?
I did a js perf here: http://jsperf.com/object-lookup-perf
I basically injected 40000 props with random keys into an object, saved the "first" and "last" keys and looked them up in different tests. I was surprised by the result, because accessing the first was 35% slower than accessing the last entry.
Also, having an object of 5 or 40000 entries didn’t make any noticeable difference.
The test case can most likely be improved and I probably missed something, but there is a start for you.
Note: I only tested chrome
Yes, something like "indexOf" searches front to back, so placing common items higher in the list will return them faster. Most "basic" search algorithms are basic top down (simple sort) searches. At least for arrays.
If you have so many properties, they must be computed, no ? So you can replace the (string, most probably) computation by an integer hash computation, then use this hash in a regular array.
You might even use one single array by putting values in the 2*ith, 2*i+1th slot.
If you can use a typed array here, do it and you could no go faster.
Set the most commonly needed properties at the top of the object literal syntax?
No. Choose readability over performance. If you've got few enough properties that you use a literal in the code, it won't matter anyway; and you should order the properties in a logical sequence.
Property lookup in objects is usually based on hash maps, and position should not make a substantial difference. Depending on the implementation of the hash, they might be neglible slower, but I'd guess this is quite random and depends heavily on the applied optimisations. It should not matter.
If #1 has no effect, should I create two separate objects, one with the most common 5% of properties, search that one first, then if the property isn't found there, then look through the object with all the less-common properties?
Yes. If you've got really huge objects (with thousands of properties), this is a good idea. Depending on the used data structure, the size of the object might influence the lookup time, so if you've got a smaller object for the more frequent properties it should be faster. It's possible that different structures are chosen for the two objects, which could perform better than the single one - especially if you know beforehand in which object to look. However you will need to test this hypothesis with your actual data, and you should beware of premature [micro-]optimisation.

Creating a list with two (or more) different types?

I'm trying to determine what the best approach would be for my problem.
I need to display a list of items, kind of like a media library.
To get all the images data I use something like...
var images = dataSource.getImages();
This returns an array of objects.
To get all the audio data I use
var audio = anotherDataSource.getAudio()
This also returns an array of objects
The problem is the two objects are similar but have different property names e.g.
images[0].title
audio[0].trackTitle
Now I need a way of uniting these two arrays into something useful. What I am trying to avoid is having to too many conditions later on when dealing with the array e.g. sorting on title.
So I'm thinking I could create a new array of 'MediaItem' objects.
The constructor for MediaItem would handle the mapping of the similar properties to a common property.
Does anyone know if this is a recognised pattern or a pattern that would better suit my needs?
Thanks

Categories

Resources