I was asked this question in an assessment I took and was not able to figure it out. Would like to know possible solutions.
Question:
Write one Javascript statement on the indicated line that will make the printed number always be between 10 and 20.
let x = 2;
let y = 8;
const a = function(b) {
return function(c) {
return x + y + Math.abs(b) + c;
};
};
// Statement will go here
const fn = a(x);
x = 4;
console.log(fn(Math.random() * 10));
I've tried assigning different values to variable y. But I think the culprit is to know what variable c would be in the nested function. Note that c would always be a number between 0 and 10 (as Math.random() is between 0 and 1, then multiplied by 10).
You already concluded correctly that the argument passed to fn is a random number between 0 and 10, which is c in the expression that the call to fn will evaluate: x + y + Math.abs(b) + c
So if fn must return a number between 10 and 20, then x + y + Math.abs(b) must equal 10.
We also see that the global variable x is set to 4 at a time that we cannot change it any more, but still before the call to fn, so that means y + Math.abs(b) must equal 6.
Now this gives us already a hint: as it stands, y is 8, which makes the conclusion in the previous paragraph impossible. So we must alter y. It is not yet too late, since the value of y will only be read when fn is called.
So what is Math.abs(b)? The local variable b is set when a is called. a is called with x, which at the time of that call is still 2. So Math.abs(b) is 2, and so we can derive that y must be 4.
One obvious way to make y to be 4 in one line:
y = 4;
(Alternatively, y-=4, y>>=1, y/=2, y^=12, ...etc)
If you want to provide a creative answer, try:
Math.random = function() { return 1.345; };
Related
I want to get the absolute value of a number in JavaScript. That is, drop the sign.
I know mathematically I can do this by squaring the number then taking the square root, but I also know that this is horribly inefficient.
x = -25
x = x * x
x = Math.sqrt(x)
console.log(x)
Is there a way in JavaScript to simply drop the sign of a number that is more efficient than the mathematical approach?
You mean like getting the absolute value of a number? The Math.abs javascript function is designed exactly for this purpose.
var x = -25;
x = Math.abs(x); // x would now be 25
console.log(x);
Here are some test cases from the documentation:
Math.abs('-1'); // 1
Math.abs(-2); // 2
Math.abs(null); // 0
Math.abs("string"); // NaN
Math.abs(); // NaN
Here is a fast way to obtain the absolute value of a number. It's applicable on every language:
x = -25;
console.log((x ^ (x >> 31)) - (x >> 31));
If you want to see how JavaScript implements this feature under the hood you can check out this post.
Blog Post
Here is the implementation based on the chromium source code.
function MathAbs(x) {
x = +x;
return (x > 0) ? x : 0 - x;
}
console.log(MathAbs(-25));
I think you are looking for Math.abs(x)
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/abs
Alternative solution
Math.max(x,-x)
let abs = x => Math.max(x,-x);
console.log( abs(24), abs(-24) );
Also the Rick answer can be shorted to x>0 ? x : -x
to simply drop the sign of a number
var x = -25;
+`${x}`.replace('-', '');
This question already has answers here:
Using comma in Javascript variable declaration [duplicate]
(2 answers)
Closed 1 year ago.
Can someone please explain the below code for me?
Is the line setting multiple variables at the same time? If so, what is are they?
If it is setting multiple variables, I would have expected all the items to be X=Y, but instead I get random variables within the line, like reevVal, mmareev, amareev, fvVal.
Any help is greatly appreciated.
var balance = $(".input-balance"), value = $(".balance-value"), reevVal, mmaVal = $(".mma-val span"), mmareev, amaVal = $(".ama-val span"), amareev, triggerPlus = "false", triggerMinus ="false", fvVal;
var x = 0, y, z = 1
is equivalent to
var x = 0;
var y; // undefined
var z = 1
There's also the similar, but different, comma operator that lets you "group" up multiple expressions into a single expression. The value of the last sub-expression is returned, but all sub-expressions are evaluated:
let x = (5, doSix(), 7); // x = 7
x = 8, doNine(), 10; // 10
Note the parens are necessary in the 1st line above to make it clear it's a single declaration and not a list of declarations like in the 1st example. The parens aren't necessary in the 2nd line, since there's not let|var|const so it's not a declaration, but an assignment.
In practice, it's most common in for loops where you're constrained to a single expression:
for (let i = 0, j = 10; i < j; i++, j--)
console.log(i, j);
I dont understand why once the condition is met and it returns [y-1] the y in parameter in the range function goes up by 1 until it reaches 9,should it not s go down until it reaches 0 based on the else condition or something like that?
function range(x, y) {
if (y - x == 2) {
return [y - 1];
} else {
var up = range(x, y - 1);
}
}
console.log(range(2, 9));
The problem you are experiencing has to do with the way your function is structured. For instance, what is the use of the variable up? All you do is assign a value, but never use it. Your intent is clear and can be stated as pseudo-code like this:
Accept two integers with the the second being at least two higher
than the first
If the second minus the first is equal to 2 then
return the second value minus one
Otherwise, subtract one from the second value and do the operation again
Here is a quick implementation of that code. Please note there is ALWAYS a return to ensure output the terminal value:
function range(x, y) {
return (y - x == 2) ? y - 1 : range(x, y - 1);
}
console.log(range(2, 9));
If you are not familiar with ternary operators, this is how they work:
( TEST ) ? Do this if TEST return true : otherwise do this
I have set a number variable under c. After running it through local storage and a couple functions, the variable has turned into a string. Instead of x adding to c , x adds a digit to c. Can anyone see the problem?
function hi() {
c += x;
document.getElementById("paragraph").textContent = "This is a string" + c;
localStorage.clocal = c;
}
function resetvar() {
c = localStorage.clocal;
}
function bla() {
if (localStorage.getItem("clocal") === "null") {
document.getElementById("parargraph").textContent = "This Works Okay";
} else {
document.getElementById("parargraph").textContent = "This is a string" + localStorage.credits;
}
}
the data put in localStorage always as string.
If you wanna to get as number that you have to parse it
like this
c = parseInt(localStorage.clocal);
That's the nature of JS. You can use parseInt(c, 10) + x or x + 1 * c to over come this.
It's a little bit difficult to follow the flow of these methods, but one glaring issue I see is this line:
c += x
In this situation, you're saying that you want to set c equal to the result of c + x where x is a string, instead of setting x equal to x + c? By making this assignment, you are converting c to a string. Then after that point is doesn't matter what else you do -- it will still be a string unless you re-assign it explicitly as an integer.
I hope I understand your intention correctly.. It is a bit unclear.
I want to get the absolute value of a number in JavaScript. That is, drop the sign.
I know mathematically I can do this by squaring the number then taking the square root, but I also know that this is horribly inefficient.
x = -25
x = x * x
x = Math.sqrt(x)
console.log(x)
Is there a way in JavaScript to simply drop the sign of a number that is more efficient than the mathematical approach?
You mean like getting the absolute value of a number? The Math.abs javascript function is designed exactly for this purpose.
var x = -25;
x = Math.abs(x); // x would now be 25
console.log(x);
Here are some test cases from the documentation:
Math.abs('-1'); // 1
Math.abs(-2); // 2
Math.abs(null); // 0
Math.abs("string"); // NaN
Math.abs(); // NaN
Here is a fast way to obtain the absolute value of a number. It's applicable on every language:
x = -25;
console.log((x ^ (x >> 31)) - (x >> 31));
If you want to see how JavaScript implements this feature under the hood you can check out this post.
Blog Post
Here is the implementation based on the chromium source code.
function MathAbs(x) {
x = +x;
return (x > 0) ? x : 0 - x;
}
console.log(MathAbs(-25));
I think you are looking for Math.abs(x)
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/abs
Alternative solution
Math.max(x,-x)
let abs = x => Math.max(x,-x);
console.log( abs(24), abs(-24) );
Also the Rick answer can be shorted to x>0 ? x : -x
to simply drop the sign of a number
var x = -25;
+`${x}`.replace('-', '');