Add entries to head of Map using immutablejs - javascript

I am working on react . using immutableJs for handling the states.
Suppose if i have Map type data. I want add the data to head.
If i use Map.set(key,value) it adds the value at tail.
For ex -
Immutable.Map({'testKey','testValue'}).set(message_id, anotherMap) // It adds the value at tail of the map.
I tried using concat https://facebook.github.io/immutable-js/docs/#/OrderedMap/concat like this -
MapIWantToAddAtHead.concat(olderMap)
but it doesn't seems to working.
I havent tried merge yet .
Is there any other way which i am missing to add entries at head.

Given you are using a Map, I take it that your use case involves keys and values. But for some reason not mentioned in your question above, you also want the new entries to come in the front. I am assuming you are doing this to be able to operate with them in LIFO fashion. And although mentioned fleetingly, you seem to be using OrderedMap which guarantees iteration order of FIFO.
If my assumptions are correct, you can simply invoke the reverse method on your OrderedMap to turn it into LIFO. This way you won't need to fiddle around with the insertion logic, and at the same time you will traverse the Map in the desired order.

Related

How to delete the first inserted item in a Map?

I want to have something like Java's linkedHashMap, where the elements in it are in insertion order, and I can extract the first inserted and/or also remove it from the map, as I need. I know that in js, by default, maps store by insertion order but I can't figure out how to both extract the value & key of the first inserted, and then remove that item(the pair) from the map. Sort of like removing the first from a queue. Given that js Maps are defaulted to be stored in insertion order, I figure this should be possible, but I don't know how to do it.
for context, I'm doing this to improve the efficiency of a leetcode question, that uses the sliding window pattern.
Well if all you want is to remove the first inserted key-value pair from a Map, then you could simply do:
map.delete(map.keys().next().value)
Depending on the requirements of the full problem you are trying to solve of course, you could optimize this by storing the keys iterator in a variable or something of the like.

What are the various parameters i can pass to <animated> from react-spring

I have just started working on react-spring. From the very beginning, I have seen the usage of '''<animated>''' tag. As, I explored more and complexity increases, I find more and more details of the code which I do not fully understand.
For example, Just have a look at this sandbox-
https://codesandbox.io/s/stupefied-noether-8i6o0
I am still not clear how the key variable passed to animated tag is working under the hood. Moreover, is there is an exhaustive list on which parameters can I pass to animated tag?
Also, is there any good tutorials/resources to understand react-spring in detail? The official document though is quite helpful, doesn't provide enough resolution on micro details of each aspect of it's function.
The key prop is not directly related to react-spring, in your example you can see that string which is an array uses the map() function to map and render animated divs.
key is used by React in order to be able to track those elements between changes and be able to determine whether the virtual DOM needs to generate those elements again as a whole or only the new ones that are added. More about keys and lists can be found here.
For more info about react-spring you might find some more information here, if you have something specific you would like to achieve feel free to make a question about it, playing with the library and experiencing it yourself will probably be the best way to learn about it.

How to add location-pin to Cartagen map?

I don't see much mention of Cartagen on stackoverflow, so please point me somewhere else if there is a better forum for this question. I am using Cartagen JavaScript library to render a map in the browser. I want to place a location pin on the map. I figure there must be an easy way to do this but I haven't been able to find it in the documentation or code.
I found a way to place a map-pin. I used User.set_loc() to set the location of the default User. Then I used User.mark() to mark that location. I changed the code in User.mark() from drawing a circle for the mark, to using ctx.drawImage() to put my .png of a map-pin on to the map. I might be able to make other pins if I make other instances of User.
This use of User.mark() did not create an object that will be automatically be used on every redraw of the map. For that I think I might have to use something like the User.add_node() and User.toggle_way_drawing() whereby a node is created, tagged with "user_submited", and put on the Geohash.objects array. The Geohash.objects array is used by Gartagen.draw() to add user-submitted objects to the Cartagen.feature_queue which are then rendered on the map.
But I haven't totally figured out the use of User.add_node() yet, so instead I added code to Cartagen.draw() to call User.set_loc() and User.mark() every time the map map is redrawn.

Visualising data with javascript graphs - dynamically

Right now I'm using plot.ly javascript library to visualise an array of numbers. I want to update this plot in every iteration. I tried to Plotly.newPlot('id',data); after values changed, however it takes time to re-define plot object every time.
I went through plot.ly documentation yet did not find a solution for my case.
I want to update graph in every interruption, maybe I need to update plot more 200 times after calling iterating function. Any solutions/suggestions for this problem? I can use another plotting library if there is one fits for this case.
Try Plotly.extendTraces
Unfortunately no official examples are available at the moment.
I'd recommend:
looking the source code here, and
the test cases here.
Bedi, unfortunately, I cannot respond to your comment directly. I don't have enough points (I need 50 and I have 15). Plotly.extendTraces() is what you need. The error you've noted is because update.y needs to be an array with a length equal to that of the indices argument to Plotly.extendTraces(). Looking at the source, indices is the third argument to the extendTraces. Your indices argument is only one item long ([0].length === 1). As long as itemList is an array of length 1 you should not be having a problem. Run console.log(itemList.length === [0].length) and I think you'll discover that you're trying to add too many points at once to your trace.

In jQuery is it more efficient to use filter(), or just do so in the each()?

I currently have code that is pulling in data via jQuery and then displaying it using the each method.
However, I was running into an issue with sorting, so I looked into using, and added, jQuery's filter method before the sort (which makes sense).
I'm now looking at removing the sort, and am wondering if I should leave the filter call as-is, or move it back into the each.
The examples in the jQuery API documentation for filter stick with styling results, not with the output of textual content (specifically, not using each()).
The documentation currently states that "[t]he supplied selector is tested against each element [...]," which makes me believe that doing a filter and an each would result in non-filtered elements being looped through twice, versus only once if the check was made solely in the each loop.
Am I correct in believing that is more efficient?
EDIT: Dummy example.
So this:
// data is XML content
data = data.filter(function (a) {
return ($(this).attr('display') == "true");
});
data.each(function () {
// do stuff here to output to the page
});
Versus this:
// data is XML content
data.each(function () {
if ($(this).attr('display') == "true") {
// do stuff here to output to the page
}
});
Exactly as you said:
The documentation currently states
that "the supplied selector is
tested against each element [...]",
which makes me believe that doing a
filter and an each would result in
non-filtered elements being looped
through twice, versus only once if the
check was made solely in the each
loop.
Through your code we can clearly see that you are using each in both cases, what is already a loop. And the filter by itself is another loop (with an if it for filtering). That is, we are comparing performance between two loops with one loop. Inevitably less loops = better performance.
I created this Fiddle and profiled with Firebug Profiling Tool. As expected, the second option with only one loop is faster. Of course with this small amount of elements the difference was only 0.062ms. But obviously the difference would increase linearly with more elements.
Since many people are super worried to say the difference is small and you should choose according to the maintainability, I feel free to express my opinion: I also agree with that. In fact I think the more maintainable code is without the filter, but it's only a matter of taste. Finally, your question was about what was more efficient and this is what was answered, although the difference is small.
You are correct that using filter and each is slower. It is faster to use just the each loop. Where possible do optimise it to use less loops.
But this is a micro optimisation. This should only be optimised when it's "free" and doesn't come at a cost of readable code. I would personally pick to use one or the other based on a style / readability preference rather then on performance.
Unless you've got a huge sets of DOM elements you won't notice the difference (and if you do then you've got bigger problems).
And if you care about this difference then you care about not using jQuery because jQuery is slow.
What you should care about is readability and maintainability.
$(selector).filter(function() {
// get elements I care about
}).each(function() {
// deal with them
});
vs
$(selector).each(function() {
// get elements I care about
if (condition) {
// deal with them
}
}
Whichever makes your code more readable and maintainable is the optimum choice. As a separate note filter is a lot more powerful if used with .map then if used with .each.
Let me also point out that optimising from two loops to one loop is optimising from O(n) to O(n). That's not something you should care about. In the past I also feel that it's "better" to put everything in one loop because you only loop once, but this really limits you in using map/reduce/filter.
Write meaningful, self-documenting code. Only optimise bottlenecks.
I would expect the performance here to be very similar, with the each being slightly faster (probably noticeable in large datasets where the filtered set is still large). Filter probably just loops over the set anyway (someone correct me if I'm wrong). So the first example loops the full set and then loops the smaller set. The 2nd just loops once.
However, if possible, the fastest way would be to include the filter in your initial selector. So lets say your current data variable is the result of calling $("div"). Instead of calling that and then filtering it, use this to begin with:
$("div[display='true']")
I generally don't worry about micro-optimizations like this since in the grand scheme of things, you'll likely have a lot more to worry about in terms of performance than jQuery .each() vs. .filter(), but to answer the question at hand, you should be able to get the best results using one .filter():
data.filter(function() {
return ($(this).attr('display')==="true");
}).appendTo($('body'));
For a primitive performance comparison between .each() and .filter(), you can check out this codepen:
http://codepen.io/thdoan/pen/LWpwwa
However, if all you're trying to do is output all nodes with display="true" to the page, then you can simply do as suggested by James Montagne (assuming the node is <element>):
$('element[display=true]').appendTo($('body'));

Categories