Sum of elements, differences between code [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have two pieces of code both calculating the sum of the elements of an array:
var sum = array.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
}, 0);
or
var sum = 0;
array.forEach(function(e) {
sum += e;
});
Are there any differences between them beside different implementations? When is it better to use which one?

Besides your personal style preference, there could be also difference in actual performance. Those two look to perform similarly however.
If you're doing this operation a lot (or for large arrays) consider using the third way:
var sum = 0;
for (l = array.length; l--; ) { sum += array[l]; }
This will be way faster. Check this performance test for actual results.
Note: you will gain some speed if you cache array length. So instead of doing this:
for (var i = 0; i < array.length; i++) {...}
Do this:
var l = array.length;
for (; l--; ) { ... }
or this:
for (l = array.length; l--;) { ... }

First one is slightly heavier than the second one.
The fastest way is to avoid calling functions for each step and use loops like for.
var sum = 0;
for(var i=0, len=array.length; i<len; i++){
sum += array[i];
}

as using both of these function involves executing the callback function for each element that would incur the function calling overhead (so both re not efficent), using loop will give better performance.

Related

Adding values to an array in JavaScript loops [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm learning JavaScript and I used the loops to add some values to an array and then print theme and see the result. I have done this with different methods but I have a problem with one of them.
In the code below I can't think of a way to add values to an array using for/in the loop. How can I do this?
<script type="text/javascript">
function print(string){
document.write(string+"<br>");
}
</script>
<script type="text/javascript">
print("with for & for..in");
var ma1Arr = [];
for (i = 10; i < 20; i++) {
ma1Arr.push(i);
}
for (i in ma1Arr) {
print(ma1Arr[i]);
}
print("<hr>");
print("with for & for..in vice versa");
var ma3Arr = [];
i=20;
for (i in ma3Arr){
ma3Arr.push(i);
i++
}
for (i=0; i<ma3Arr.length; i++){
print(ma3Arr[i])
}
print("<hr>");
print("with while & do..while");
var ma2Arr = [];
i = 30;
do {
ma2Arr.push(i);
i++;
} while (i < 40);
i = 0;
while (i < ma2Arr.length) {
print(ma2Arr[i]);
i++;
}
print("<hr>");
print("with while & do..while vice versa");
var ma4Arr = [];
i = 40;
while (i<=50){
ma4Arr.push(i);
i++;
}
i = 0
do {
print(ma4Arr[i]);
i++;
}while (i<ma4Arr.length);
</script>
for...in is used for objects like {a: 1, b: 4} and not for arrays. It is iterating all enumerable properties of the object such as a and b. But for arrays, you would need to go with for...of
for..in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
for...of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
var array_name = [item1, item2, ...];
You put the values inside of the brackets... That is basically how you make an array for any language

How to select pairwise element from two array and give them to two different function in JavaScript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have an array of getters G = ["g1", "g2", "g3"]and another array of setters S = ["s1", "s2"]. Further I have following two functions
callGetters(index???) {
targetParameter = G[index???];
}
callSetter (index???) {
targetParameter = S[index???]
}
Now, I am trying to call above two functions with this pairwise sequence of selected/picked parameters i.e.
choose g1, s1 then callGetters()/callSetter ()
.. g1, s2, then callGetters/callSetter ()
...g2, s1, then callGetters()/callSetter ()
...g2,s2, then callGetters()/callSetter ()
.. g3, s1, then callGetters()/callSetter ()
..g3, s2, then callGetters()/callSetter () ..
I could not imagine how to code the above scenario in javascript/nodejs. I am newbie in JavaScript/Nodejs, so accept my apology, if this is not asking in a standard way or not used proper terminologies...
for(let i = 0; i < G.length; i++){
for(let j =0; j < S.length; j++){
console.log(G[i],S[j])
//do whatever
}
}
you can try two for loops like above.

What is the most idiomatic way to handle variables declared in multiple for loops? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
JavaScript only has function scope. Thus, variables declared in for loops are visible for the entire function.
For example,
function foo() {
for(var i = 0; i < n; i++) {
// Do something
}
// i is still in scope here
}
When we have multiple for-loops, this opens the question of how we handle the variables in these other for loops.
Do we use a different variable?
for(var i = 0; i < n; i++) { }
for(var j = 0; j < n; j++) { }
Or do we use the same variable but just assign a value (instead of declaring it)?
for(var i = 0; i < n; i++) { }
for(i = 0; i < n; i++) { }
Or declare i outside of the loops?
var i;
for(i = 0; i < n; i++) { }
for(i = 0; i < n; i++) { }
Or redeclare i?
for(var i = 0; i < n; i++) { }
for(var i = 0; i < n; i++) { }
All of these work (or at least they do on the latest versions of my browsers). JSHint doesn't like the last approach, though.
Is there an approach which is most idiomatic or otherwise preferable?
It really depends on who you're coding for. If you're coding for a company or contributing to a library you of course follow their style guide. I've seen all of these (expect the last) used in libraries. If you like the Douglas Crockford style you'll go with the second to last and place all your variables at the top of function scope (or jslint will shout at you).
Taking an example from the jQuery style guide:
This is considered Good style
var i = 0;
if ( condition ) {
doSomething();
}
while ( !condition ) {
iterating++;
}
for ( ; i < 100; i++ ) {
object[ array[ i ] ] = someFn( i );
}
While this is poor style:
// Bad
if(condition) doSomething();
while(!condition) iterating++;
for(var i=0;i<100;i++) object[array[i]] = someFn(i);
Anyway, because this is style I'm going to reference how several libraries write their for each loops:
jQuery uses the Crockford style in core as does lodash
Underscore js uses the last style as seen here. Mootools also uses this style
If your code is going to be minimized before you release it, it will not matter as minifiers will mangle it to pretty much the same end representation in the processing.
Using different variables we have no problems.
Reusing and reassigning makes the code less readable, and if we remove the declaration at a later time, we risk assigning i to something outside of the function scope.
Declaring i outside the loops, we have no problems.
Redeclaring will be an issue if your lint tool, IDE, etc complain.
So I would argue for the first or third option. If number of variables is a concern using the first option, then you are may be in need of a refactoring.
Another take that answers the question in a different way.
A function with multiple loops makes me suspicious because:
It may be doing too much and should be decomposed anyway, and
It may be better to write it more functionally and eliminate the index altogether (it's available in some each-/map-y functions anyway)
Another approach is to use iterator functions. For example, in modern browsers an Array will have a forEach method:
var items = ["one", "two", "three"];
var things = ["hello", "goodbye"];
items.forEach(function (item, index) {
// Do stuff
});
things.forEach(function (item, index) {
// Do stuff
});
If you're using older browsers (or custom collections), you can make your own iterator like this:
Array.prototype.forEach = function(callback) {
for(var i = 0; i < this.length; i++) {
callback.apply(this, [this[i], i, this]);
}
};
For more information see: Array.prototype.forEach()
Any variables declared within a function are interpreted as being declared at the beginning of the function. Doug Crockford argues that you should declare all of your variables at the first line of every function.
doSomething = function() {
var i, ... other variables ...;
...
for (i = 0; i < x; i += 1) {
...
}
...
for (i = 0; i < x; i += 1) {
...
}
}
This way the code reads in the same way it will be parsed by the javascript engine.

Explicit conditions of breaking a loop at the top of the loop [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have the following loop, which loops through required_types array and finds linked objects:
for (var i = 0; i < required_types.length; i++)
{
var linked_objects =linker.linked(required_types[i].type);
}
Now, I want to break the loop once I've found the type which has more than 0 objects linked, so in an accustomed way I'd do it like that:
var has_linked_objects = false;
for (var i = 0; i < required_types.length; i++)
{
var linked_objects = ctx.linker.linked(required_types[i].type);
var has_linked_objects = linked_objects > 0;
if (has_linked_objects)
{
break;
}
}
However, I've recently read interesting chapter from Code Complete which states that exists from a loop should be as clear as possible and be stated in the beginning of the loop. This allows a reader to know all possible exit conditions before even examining the loop. So now I would write the loop in this way:
var has_linked_objects = false;
for (var i = 0; i < required_types.length && has_linked_objects === false; i++)
{
var linked_objects = ctx.linker.linked(required_types[i].type);
var has_linked_objects = linked_objects > 0;
}
Is the second option really a better choice that the first one? If so, why?
IMHO, this is bad advice. The condition could get very long and it no longer matches my mental "for-each" pattern.
I read this
for (var i = 0; i < required_types.length; i++) {
if (has_linked_objects) {
break;
}
}
as
for each element in required_types { // easy
if(found) {
break;
}
}
And I read this
for (var i = 0; i < required_types.length && has_linked_objects === false; i++) {
}
as
Wow, this is a complicated loop! Let me read this carefully...
When does has_linked_objects change?
Could it change to true and change back to false in a single iteration of the loop?
I think it's much easier to think about simple conditions: “if this happens, then break” than to keep track of many variables in the loop body and test everything at once in the next iteration. The second approach could make it harder to write the rest of the function, because you can't be sure which condition triggered the end of the loop (was the element found or not?)
You can use some method like this
if (required_types.some(function(cType){return ctx.linker.linked(cType) > 0;})) {
...
}
This breaks out of iterating the Array at the first iteration which returns true. If I have to choose between the two options you provided, I would choose the second (with the following fixed code)
var has_linked_objects = false;
for (var i = 0; i < required_types.length && has_linked_objects === false; i++)
{
has_linked_objects = ctx.linker.linked(required_types[i].type) > 0;
}
It is right, that you should put all conditions in the head of the loop if possible. If it is not possible or if it would make the code even less readable, you can - of course - use a break. In your case the loop is so small and simple that it probably won't make a huge difference. If you really want to make sure that fellow developers know what's going on, you can still write a comment that lists alternative exit points in the loop.
// Iterates required_types and breaks on an entry with linked objects
for (var i = 0; i < required_types.length; i++)
{
...
if (has_linked_objects)
{
break;
}
}
If you need to further use the last used element in the array, having the second condition in the head of the loop introduces another issue. When the loop ends, i will always be 1 higher than your result. You will have to decrease i by one after the loop. Not that it's complicated to do that, but I, as someone who reads the code, would be confused for a second or two.
for (var i = 0; i < required_types.length && has_linked_objects === false; i++)
{
...
}
i--; // This can easily get overread or misinterpreted
var obj_with_linked_objects = required_types[i];
TL/DR: I personally prefer break in this case.

How to improve selection sort? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
This is more of an academic/homework question?
Would it be better to change
if (index_outer !== index_min) {
$P.swap(arr, index_outer, index_min);
}
to
$P.swap(arr, index_outer, index_min);
and always swap, as this is the special case when index_outer does have the smallest value? It would be a swap that does nothing, but at the same time it would not break anything. Because this does not happen often I suppose, it would reduce the amount of times an if check was used.
$P.swap = function (arr, i, j) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
};
$P.selectionSort = function (arr) {
var index_outer,
index_inner,
index_min,
length = arr.length;
for (index_outer = 0; index_outer < length; index_outer++) {
index_min = index_outer;
for (index_inner = index_outer + 1; index_inner < length; index_inner++) {
if (arr[index_inner] < arr[index_min]) {
index_min = index_inner;
}
}
if (index_outer !== index_min) {
$P.swap(arr, index_outer, index_min);
}
}
return arr;
};
I don't think it would always be a good idea. What if array was partially/fully sorted, you would be wasting a call to $P.swap().
As for improving selection sort try sorting the array from both ends simultaneously by taking index_min and index_max. Though number of comparisons would remain same, number of passes would decrease hence decreasing total run time.

Categories