Range in Javascript [duplicate] - javascript

This question already has answers here:
Does JavaScript have a method like "range()" to generate a range within the supplied bounds?
(88 answers)
Closed 3 years ago.
can I please ask how to make a range in Javascript? For example if I need to print letters "A" to "E" or number 1 to 5. For example in Ruby it is simple double dot like this (1..5).
I tried this code but it gives error.
let letter = range("A", "E");
console.log(letter);
Thank You

For numbers you can use ES6 Array.from(), which works in everything these days except IE:
Shorter version:
Array.from({length: 20}, (x,i) => i);
Longer version:
Array.from(new Array(20), (x,i) => i)
which creates an array from 0 to 19 inclusive. This can be further shortened to one of these forms:
Array.from(Array(20).keys())
// or
[...Array(20).keys()]
Lower and upper bounds can be specified too, for example:
Array.from(new Array(20), (x,i) => i + *lowerBound*)
An article describing this in more detail: http://www.2ality.com/2014/05/es6-array-methods.html

Javascript doesn't include that feature, but you can use Lodash which is javascript library which include that feature, and It's only for number.
But you can create your self function which generate range of number and for letters

Related

what does '&' do in this solution? [duplicate]

This question already has answers here:
How does '&' work in relation to odd and even? In JS
(3 answers)
Closed last month.
I'm working through a problem on CodeSignal and trying to understand some of the solutions that other people have submitted. One of the solutions was as follows, and I don't understand what the ampersand is doing.
(a) => a.reduce((p,v,i) => (p[i&1]+=v,p), [0,0])
The problem is:
Several people are standing in a row and need to be divided into two teams. The first person goes into team 1, the second goes into team 2, the third goes into team 1 again, the fourth into team 2, and so on.
You are given an array of positive integers - the weights of the people. Return an array of two integers, where the first element is the total weight of team 1, and the second element is the total weight of team 2 after the division is complete.
Example
For a = [50, 60, 60, 45, 70], the output should be
solution(a) = [180, 105].
In this solution, the & operator is used to perform a bitwise AND operation. In JavaScript, the & operator compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
In the given solution, the & operator is used to determine whether the index i of the current element in the array is even or odd. If i is even, the result of i & 1 will be 0. If i is odd, the result of i & 1 will be 1.

How does JavaScript engine compute arithmetic expression? [duplicate]

This question already has answers here:
Why does changing the sum order returns a different result?
(7 answers)
In which order should floats be added to get the most precise result?
(11 answers)
How to deal with floating point number precision in JavaScript?
(47 answers)
Closed 5 months ago.
Quick summary - I was running a piece of code(in React application) where I am summing up decimal values entered by a user. One of the conditions to move to next page is if the sum equals 100
Problem - In one case, the sum of all values (a+b+c+d+e+f) is being computed to 99.99999999999997 even though the summation(over a calculator) is 100. But when I change the summation order to a+d+e+f+b+c, the sum is correctly computed to 100.
Please find below code samples -
Wrong summation -
const result = [15+10.4+1.9+1.9+4.9+2.8+6.8+2+4.9+2.8+2.5+2.8+4.8+6.5+15+15].reduce((sum, val) => {return sum+val}, 0)
console.log(result) //99.99999999999997
Correct summation -
const result = [15+10.4+4.9+2.8+6.8+2+4.9+2.8+2.5+2.8+4.8+6.5+15+15+1.9+1.9].reduce((sum, val) => {return sum+val}, 0)
console.log(result) //100
Questions -
How does JavaScript engine compute?
How to compute to 100 always (without using ceil, floor or round methods because Math.round(99.6) is also equal to 100.

functional loop given a number instead of an array [duplicate]

This question already has answers here:
Tersest way to create an array of integers from 1..20 in JavaScript
(16 answers)
Closed 6 years ago.
The community reviewed whether to reopen this question 2 months ago and left it closed:
Original close reason(s) were not resolved
Say I have a number 18, instead of an array, in hand.
What is the best way to create a functional loop in JS given a number X instead of array of X elements?
I can do this:
[1,2,3].forEach(function(){
));
but if I have the number 3
I can do
for(var i = 0; i < 3; i++){
}
but I want that loop to be functional instead
If you have a number and you want to create a loop then you can use the number in limiter condition in the for loop.
for(var i = 0; i < number; i++)
Edit 1: you can use foreach on arrays only, in that case since you have a number already you can create a array of that length and then use the foreach on it.
var foo = new Array(number).fill(0);
foo.foreach()
Also another option is
var N = 18;
Array.apply(null, {length: N}).map(Number.call, Number)
result [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
Many more options available in this thread Create a JavaScript array containing 1...N
I don't understand why you want to do this. An equivalent to:
[1,2,3].forEach(function(){ ... ));
Is
var limit = n;
while (--limit) {( // Note: 0 is falsy
function(){ ... }
)(limit);}
Or if you really want to use an array structure, the following will do:
new Array(limit).fill(0).forEach(function(){...});
You might be interested in Myth of the Day: Functional Programmers Don't Use Loops.
Per this question, you can "functionally" iterate over a linear sequence relatively easily using:
Array.apply(null, Array(number)).map(function () {}).forEach(...)
Not sure what advantage this gives you versus a regular for-loop with an index, though it is a neat trick.

JavaScript Array.sort doesn't work on some arrays of numbers [duplicate]

This question already has answers here:
How to sort an array of integers correctly
(32 answers)
Closed 9 years ago.
I'm trying to use JavaScript's sort function on arrays of numbers and sometimes it doesn't do anything:
var a = [200,20].sort(); // [20,200]
var b = [200,21].sort(); // [200,21]
jsfiddle
Javascript sorts everything as strings (=alphabetically) by default. The string "200" is less than the string "21". To sort as numbers you have to tell it so:
[200,21].sort(function(a,b) { return a-b })
Yep, this is the standard behaviour for "sort" because it perform "string" reordering. If you want to sort by number value you must pass a "compare" function to sort, like this:
[200,21].sort(function (a, b) {
return a-b;
})
// [21, 200]
The function must return 0 for identical value, n < 0 if a < b and n > 0 if a > b. For that reason, the difference is enough to provide sorting (assuming that you're not using huge numbers)

How to find difference between two values? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I want return the difference between 2 values how to do that?
0.0.0.1.0 and 0.0.0.1.12
so the difference between these two values is 12
so how to calculate that I tried with Math.abs() but it is fine with single digits.
Assuming that they are strings (since you can't have more than 1 full stop in a valid JS number), you could split it by . character and calculate the difference of individual components:
function numStringDiff(a, b) {
// split them on dot characters
const aParts = a.split('.');
const bParts = b.split('.');
// loop using longest array length as a container for mapped results
return Array(Math.max(aParts.length, bParts.length)).fill(undefined).map((_, i) => {
const i1 = parseInt(aParts[i] || 0); // fetch aParts[i] or default to 0
const i2 = parseInt(bParts[i] || 0); // fetch bParts[i] or default to 0
// return compared value after defaulting the values.
return i2 - i1;
});
}
console.log(numStringDiff('0.0.0.1.0', '0.0.0.1.12'));
The problem here is that, as you stated in the comments, they can be of different length. To make it work in this scenario, we must iterate an amount of times equal to the length of the longest array and ensure that any missing items in the shorter one are defaulted to some non-breaking value like 0 so that we can safely subtract every digit present in the longest list with something or 0.
Note that 0 is a value I only used to ensure you can calculate a difference between different-length arrays, choose any (numeric or float) value that fits your needs.
If in this case the second argument has less dots than the first, negative difference will be returned, otherwise if first is longer than last, positive difference will be returned.
Some examples:
numStringDiff('1.1.1', '1.1') // => [0, 0, -1]
numStringDiff('1.1', '1.1.1') // => [0, 0, 1]
numStringDiff('1.1.1', '1.1.1') // => [0, 0, 0]
For the absolute distance between two values, one can simply .map over this array:
numStringDiff('1.1.1', '1.1').map(num => Math.abs(num));
// OR, using short form:
numStringDiff('1.1.1', '1.1').map(Math.abs);
And finally, should you need the result as a string, simply .join it back together with '.':
numStringDiff('1.1.1', '1.1').map(Math.abs).join('.');
Do know what you are trying to achieve though. If you're trying to manually bisect version numbers (like semver versions) I'd recommend against it since there will always be scenario's uncovered by this function such as pre-releases that wouldn't include only digits but rather 0.0.0-pre-foo-version or something. Since I don't know what it is you're trying to do exactly I'll leave that a responsibility for you to figure out :)

Categories