How to store data into variable.? - javascript

var a=1800, b=10;
if (a == b) {
document.write(a - b) = c;
}
else if (a > b) {
document.write(a - b) = c;
}
else {
document.write("Everything is wrong.") = c;
}
var x = c * 100;
document.write(x);
Hello friends, Can i store result of variable into "c". if yes then why i am not able to use the data for arithmetic calculations further.
I am getting 1790 as answer from if else statement.

The variable should be on the left side of the equals sign. document.write doesn't return a value so you should do the assignment before that line.
else if (a > b) {
c = a - b;
document.write(c);
}

That isn't really even valid JavaScript.
You're calling a function (document.write()) and then using the assignment operator on it (which you can't do).
The end results would be equivalent of writing something like undefined = 7 since JavaScript will evaluated/execute the function first.
C is also never declared anywhere so you'll have a problem with that potentially as well.
Instead you'll want to do something like this:
let c; //declare C but don't assign it a value
const a = 1800;
const b = 10;
if(a === b || a > b){ //Since you're doing the same thing combine the conditions
c = a - b;
document.write(c);
} else {
document.write("Somethings wrong")
}
let x = c * 100; // If c is undefined you'll get NaN similar to above, otherwise you'll get a result
document.write(x);

Firstly you should initialize your variables, then else if statement doesn't make any sense because in if your are doing the same thing which you could do with || OR operator.
const a = 1800;
const b = 10;
let c = null;
if (a == b || a > b) {
c = (a - b) * 100;
} else {
c = "Everything is wrong.";
}
document.write(c);

Document.write does not return the result of the equation, and your assignments are incorrect. When assigning variables think of it this way:
"I have a variable C. I would like C to store the value of Y."
So C = Y. It's backwards from the way math does it. ( Equation = result. ) In programming, it tends to be StorageLocation = Equation.
Why do I say tends to be? There's got to be a language out there that doesn't hold up to that paradigm!
Here's your updated code:
var a=1800, b=10, c = 0; // Initializing c for document.write is a good practice.
if (a == b) {
c = a-b;
}
else if (a > b) {
c = a-b; /* As the other two posters noticed ... this does the same thing as the a == b. I am assuming you'd like to do something a little different with the two blocks. */
}
else {
c = "Everything is wrong.";
}
document.write(c); // "Don't Repeat Yourself" or "DRY" is good practice.
var x = c * 100; // Note - Multiplying your string by 100 is weird.
document.write(x);

Related

Crypto-Js library's hmac-256 script returning function structure instead of value within Google Apps Script, working fine outside?

I am setting up a google spreadsheet project to connect to my CryptoExchange
API.
But when it comes to this simple CryptoJs Hmac-sha256 script, it's not working: it is returning the function structure instead of the value, while outside it's working fine (see my jsfiddle).
Now, I understand from this Stack answer by Cameron Roberts that Apps Script behaves differently under certain POVs, but I can't understand how this relates.
Besides, if I just switch script and use the Stanford Javascript Crypto
Library, the code executes perfectly with no issue at all, both within Google
Apps Script AND outside of it of course.
Here is my code:
eval(UrlFetchApp.fetch('https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/hmac-sha256.js').getContentText());
function write() {
var hash = CryptoJS.HmacSHA256("message", "secret");
return hash;
}
Logger.log(write());
and the console log from Google Apps Script
[19-06-07 00:53:32:859 PDT] {mixIn=
function (a) {
for (var c in a) {
a.hasOwnProperty(c) && (this[c] = a[c]);
}
a.hasOwnProperty("toString") && (this.toString = a.toString);
}
, extend=
function (a) {
q.prototype = this;
var c = new q();
a && c.mixIn(a);
c.hasOwnProperty("init") || (c.init = function () {
c.$super.init.apply(this, arguments);
});
c.init.prototype = c;
c.$super = this;
return c;
}
, init=
function (a, c) {
a = this.words = a || [];
this.sigBytes = c != s ? c : 4 * a.length;
}
, random=
function (a) {
for (var c = [], d = 0; d < a; d += 4) {
c.push(4294967296 * h.random() | 0);
}
return new r.init(c, a);
}
, words=[-1.956689808E9, 6.97680217E8, -1.940439631E9, -5.01717335E8, -
1.205480281E9, -1.798215209E9, 1.0131952E8, 1.469462027E9], clone=
function () {
var a = m.clone.call(this);
a.words = this.words.slice(0);
return a;
}
, sigBytes=32.0, create=
function () {
var a = this.extend();
a.init.apply(a, arguments);
return a;
}
, toString=
function (a) {
return (a || k).stringify(this);
}
, concat=
function (a) {
var c = this.words, d = a.words, b = this.sigBytes;
a = a.sigBytes;
this.clamp();
if (b % 4) {
for (var e = 0; e < a; e++) {
c[b + e >>> 2] |= (d[e >>> 2] >>> 24 - 8 * (e % 4) & 255) << 24 -
8 * ((b + e) % 4);
}
} else {
if (65535 < d.length) {
for (e = 0; e < a; e += 4) {
c[b + e >>> 2] = d[e >>> 2];
}
} else {
c.push.apply(c, d);
}
}
this.sigBytes += a;
return this;
}
, clamp=
function () {
var a = this.words, c = this.sigBytes;
a[c >>> 2] &= 4294967295 << 32 - 8 * (c % 4);
a.length = h.ceil(c / 4);
}
, $super={extend=
function (a) {
q.prototype = this;
var c = new q();
a && c.mixIn(a);
c.hasOwnProperty("init") || (c.init = function () {
c.$super.init.apply(this, arguments);
});
c.init.prototype = c;
c.$super = this;
return c;
}
, mixIn=
function (a) {
for (var c in a) {
a.hasOwnProperty(c) && (this[c] = a[c]);
}
a.hasOwnProperty("toString") && (this.toString = a.toString);
}
, init=
function () {
}
, clone=
function () {
return this.init.prototype.extend(this);
}
, create=
function () {
var a = this.extend();
a.init.apply(a, arguments);
return a;
}
}}
While the same code within jsfiddle works fine
EDIT:
While my question is still a source of curiosity for me, I have just found a whole branch of replies here on stack which involve a specific method within Google Apps Script I didn't know about: a built in Class Utility for creating HMAC Sha256 signature.
This may not be the very answer to my question in terms of theoretical knowledge, but will probably solve my problem from a practical point of view; so I will look into that now.
Thanks
Generate a keyed hash value using the HMAC method with Google Apps Script
How to get Hex value from computeHmacSha256Signature method of Google Apps Script?
get back a string representation from computeDigest(algorithm, value) byte[]
You want to retrieve the value of 8b5f48702995c1598c573db1e21866a9b825d4a794d169d7060a03605796360b from CryptoJS.HmacSHA256("message", "secret") using Google Apps Script.
If my understanding is correct, how about directly calculating the value using the methods of Google Apps Script? In this case, CryptoJS is not used. Please think of this as just one of several answers.
Sample script:
var res = Utilities.computeHmacSha256Signature("message", "secret")
.map(function(e) {return ("0" + (e < 0 ? e + 256 : e).toString(16)).slice(-2)}).join("");
Logger.log(res)
Result:
8b5f48702995c1598c573db1e21866a9b825d4a794d169d7060a03605796360b
Note:
The important point for above script is as follows.
At Google Apps Script, the data which was encrypted by Utilities.computeHmacSha256Signature() is the bytes array of the signed hexadecimal.
In your case, the bytes array is converted to the unsigned hexadecimal.
References:
computeHmacSha256Signature(value, key)
map()
If I misunderstood your question and this was not the direction you want, I apologize.

How do I add two numbers in JavaScript "without using `+` or `-` operators"?

I know an alternative to using the + sign for addition is to do something like this:
int add(int a, int b)
{
if(b == 0)
return sum;
sum = a ^ b;
carry = (a & b) << 1;
return add(sum,carry);
}
But I have two problems:
This is C++, not JavaScript. Is this supported in JavaScript?
It's obvious the whole trick is in ^ & <<, but I don't know how to start looking for them in JavaScript, because I don't know what they are called.
What should I be googling for even?
I tried to write this in JavaScript ... but seems I miss something
var getSum = function(a, b) {
return (a ^ b, (a & b) << 1)
};
We will use bitwise operators and will use recursion.
We use this method when we have a few low resources. Read more about when to use this method!
var getSum = function(a, b) {
if (b == 0) {
return a;
} else {
return getSum(a ^ b, (a & b) << 1)
}
};
ECMAScript 6 one-liner solution as suggested by #PatrickRoberts:
const getSum = (a,b) => b ? getSum(a ^ b, (a & b) << 1) : a;
Another solutions:
2- Arrays technique Array.prototype.fill()
const getSum = (a, b) => {
const firstArr = new Array(a).fill(true);
const secondArr = new Array(b).fill(true);
return firstArr.concat(secondArr).length
}
3- workaround to use plus sign without writing it:
const getSum = (a, b) => eval(''.concat(a).concat(String.fromCharCode(0x2B)).concat(b));
Well ok i am answering to the question as clearly described in the header. No + and no - operations right..? Yet... not with bitwise but with pure math should be a valid answer i suppose.
var x = 1,
y = 2,
sum = Math.log2(2**x * 2**y);
console.log(sum);
const add = (a, b) => new Function('a', 'b', `return ${a} ${String.fromCharCode(43)} ${b}`)(a, b);
We can implement same using while loop. We have to shift the carry to left and add it to binary sum of numbers till there will no carry. (As we follows the practice in addition of decimals.)
function getSum(a, b){
while(b!=0){
var carry = a&b; //calculate if is there any carry we need to add
a = a^b; // a is used to hold the sum
b = carry<<1; //b is used to hold left shift carry
}
return a;
}
document.write(getSum(7, 5))
It's possible to use arrays structures to perform a sum operation.
function getSum(a, b){
return Array(a).concat(Array(b)).length / 100;
}
Each input is coerced to an array, for instance, an input of value 5 would be coerced to an array of 5 elements. After coercing both inputs, the arrays are joined into a single array. The length of the final array is returned, by dividing to 100 to deal with the sum of decimal values.
Now, let's try to be defensive about invalid input cases, such as strings or falsy values.
const DEFAULT_NUMBER_VALUE = 0;
const DEFAULT_PRECISION = 100;
function parseAddInput(input){
if (!input) {
return DEFAULT_NUMBER_VALUE;
}
if (typeof input === 'string'){
input = parseInt(input);
}
const roundedNumber = Math.round(input * (10 * DEFAULT_PRECISION));
return roundedNumber;
}
function getSum(a, b){
return Array(
parseAddInput(a)
).concat(
Array(parseAddInput(b))
).length / 100;
}
function add(number1, number2){
return getSum(number1, number2);
}
The same approach as #PatrickRoberts suggested, but without recursion:
const add = (a, b) => {
let c;
while (a !== 0) {
c = b & a;
b = b ^ a;
c = c << 1;
a = c;
}
return b;
};

Javascript cannot return values

I want to get the values a, b, c from these functions and use them in my total. I have tried to return the values but it doesn't work. When I create global variables, total always takes the original global variable instead of the one from the function.
function d1() {
var a = document.getElementById("s1").value;
document.getElementById("d1").innerHTML = (2 * a).toFixed(2);
return a;
}
function d2() {
var b = document.getElementById("s2").value;
document.getElementById("d2").innerHTML = (3 * b).toFixed(2);
return b;
}
function d3() {
var c = document.getElementById("s3").value;
document.getElementById("d3").innerHTML = (4 * c).toFixed(2);
return c;
}
var total = a + b + c;
document.getElementById("total").innerHTML = total.toFixed(2);
I think it should be
var total = d1() + d2() + d3();
Since variables a, b and c are local to the functions and they fall into those functions scope. However, the biggest problem is that you do not call the functions at all, so even with using global variables your a,b,c would be undefined.
a, b and c are local variables within d1, d2 and d3 respectively. So, you can't use them directly outside of their scope like you have tried to.
There are multiple ways of achieving your desired outcome. The easiest
function d1() {
var a = document.getElementById("s1").value;
document.getElementById("d1").innerHTML = (2*a).toFixed(2);
return a;
}
function d2() {
var b = document.getElementById("s2").value;
document.getElementById("d2").innerHTML = (3*b).toFixed(2);
return b;
}
function d3() {
var c = document.getElementById("s3").value;
document.getElementById("d3").innerHTML = (4*c).toFixed(2);
return c;
}
**var total = d1() + d2() + d3();**
document.getElementById("total").innerHTML = total.toFixed(2);

alter the direction of loop dynamically

I am trying to come up with an algorithm for an "approaching" behavior between two integers. Basically, given two integers, a and b, i want a to "approach" b, even if b is less than a. The way i think this should look is a swapping of the loop incrementer function:
for (var i = a; approachCond(i, a, b); approachDir(i,a, b)) {
// some fn(a, b);
}
where
approachCond(i, a, b) {
return a < b ? i < b : i > b;
}
and
approachDir(i, a, b) {
return a < b ? i++ : i--
}
However, when i try doing this the browser freezes (Chrome). Does anyone know how to dynamically alter the direction of a loop?
I think it's a little clearer to read if you just use a while loop:
'use strict';
let a = 12, b = 6;
let i = a;
while (i !== b) {
console.log(i);
i += a < b ? 1 : -1;
}
I even left the cute ternary since people seem so opposed to if-statements these days.
Your browser freezes because you're not altering the correct i. You're only manipulating the i that is in the approachDir function. If you return it & set the for scope i to the new value, it will work.
Try:
for (var i = a; approachCond(i, a, b); i = approachDir(i,a, b)) {
// some fn(a, b);
}
approachDir(i, a, b) {
return a < b ? i + 1 : i - 1
}
It seems as though you are overcomplicating something that is not that hard. You can just set the step to positive or negative. e.g.
var a = 20;
var b = 5;
for (var step = a > b ? -1 : +1; a != b; a += step)
{
console.log(a);
}
The problem is in approachDir. i++ and i-- are post-increment and post-decrement. That means they update the variable after they return its original value. So the function is returning the original value, not the updated one. To update the variable before returning, you should use ++i or --i.
But you don't need to use an increment operator at all, since the local variable is going away immediately. Just return the new value.
function approachDir(i, a, b) {
return a < b ? i + 1 : i - 1;
}
You also need to reassign the variable in the loop:
for (var i = a; approachCond(i, a, b); i = approachDir(i, a, b)) {
...
}
The way you wrote your code, you assumed that variables are passed by reference, not by value, so that the increment in the function would modify the caller's variable.
One option is to change approachDir to return a positive or negative value based on if a>b. The middle statement can include an || and work either way.
function approachDir(a, b){
return a>b?-1:1;
}
var a=3;
var b=1;
for (var i = a; i<b||i>b; i+=approachDir(a, b)) {
console.log(i);
}
a=1;
b=3;
for (var i = a; i<b||i>b; i+=approachDir(a, b)) {
console.log(i);
}
I made a slight change to #mathletics answer:
function loopDynamic(from, to) {
const direction = from < to ? 1 : -1;
let i = from
while (i!== to) {
// do whatever with i
i += direction;
}
}

javascript - where should I put "var" in order to get specifc values

That's a code fragment task - you should enter "var" (as many as want) in it in order to get 17 in the first, and 21 in the second alert. I thing that I have met this before, but still was not able to solve the issue.
a = 3;
b = 2;
function line(x) {
a = 5;
b = 4;
return a*x + b
}
//b should be 17
b = line( a ) - b;
alert( b );
//c should be 21
c = line ( a ) + b;
alert(c);
If you put "var" in the function in front of b, it will alert "17". The next alert gives us 46 because of the new value of b, return by the function.
function line(x) {
a = 5;
var b = 4;
return a*x + b
}
That's the source of the task:
http://www.codecademy.com/courses/javascript-for-jquery/1?curriculum_id=4fc3018f74258b0003001f0f/#!/exercises/3
Using exactly what's given, in exactly the way it's given is impossible.
What I mean by that is if the call:
c = line(a) + b;
is dependent upon the value of b which is the assignment at:
b = line(a) - b;
Then it's 100% impossible to either have made a a significantly-small number, or made b a significantly-large negative number to make the math work.
Therefore it's my belief that they're intended to be two separate checks.
Best-case scenario, if we're trying to have b=17 included:
a = 3;
3 * 5 = 15 + 4 = 19 + 4 = 23;
That's the smallest you're going to get, assuming you run the two back-to-back.
Even if you did it that way, you wouldn't get b = line(a) - b = 17 on the first run...
If it was written:
c = line(a) - b;
d = line(a) + b;
Then you could run both in succession and get the expected result.
Or you can run:
var a = 3,
b = 2;
function line (x) {
var a = 5,
b = 4;
return a*x + b;
}
b = line(a) - b;
and get 17.
Then you can run:
var a = 3,
b = 2;
function line (x) {
var a = 5,
b = 4;
return a*x + b;
}
c = line(a) + b;
(ie: the exact same setup with a different instigator, and without the saved b value from the return of the previous call), and get the desired result.
But it's not possible to run both of them one after the other, and expect to have them both work, without doing anything to the code but add a var or four.
Keep your function like this, if you want to maintain consisitency. Using "var" before a and b will make them local to the function block and that call. Otherwise they will refer to the global variable.
function line(x) {
var a = 5;
var b = 4;
return a*x + b
}

Categories

Resources