Javascript If Else Statement with mathFoor and mathRandom not working - javascript

Hello i am having some troubles with my code i am fairly new to this if anyone could assist me Thanks.
var a = 5;
var b = 6;
var c = 7;
document.write(Math.floor((Math.random() * 3) + 5));
if (5) {
alert("mission failed we will get them next time");
} else {
alert("sorry");
}

Please start with learning documentation => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else
let RandomVal = Math.floor((Math.random() * 3) + 5);
console.log(RandomVal);
if (RandomVal===5) {
console.log("mission failed we will get them next time");
} else {
console.log("sorry");
}

Related

How to add "IF result = X" than "RETURN x" to this javascript code?

My Code:
const crypto = require('crypto');
const crashHash = '';
// Hash from bitcoin block #610546. Public seed event: https://twitter.com/Roobet/status/1211800855223123968
const salt = '0000000000000000000fa3b65e43e4240d71762a5bf397d5304b2596d116859c';
function saltHash(hash) {
return crypto
.createHmac('sha256', hash)
.update(salt)
.digest('hex');
}
function generateHash(seed) {
return crypto
.createHash('sha256')
.update(seed)
.digest('hex');
}
function divisible(hash, mod) {
// We will read in 4 hex at a time, but the first chunk might be a bit smaller
// So ABCDEFGHIJ should be chunked like AB CDEF GHIJ
var val = 0;
var o = hash.length % 4;
for (var i = o > 0 ? o - 4 : 0; i < hash.length; i += 4) {
val = ((val << 16) + parseInt(hash.substring(i, i + 4), 16)) % mod;
}
return val === 0;
}
function crashPointFromHash(serverSeed) {
const hash = crypto
.createHmac('sha256', serverSeed)
.update(salt)
.digest('hex');
const hs = parseInt(100 / 4);
if (divisible(hash, hs)) {
return 1;
}
const h = parseInt(hash.slice(0, 52 / 4), 16);
const e = Math.pow(2, 52);
return Math.floor((100 * e - h) / (e - h)) / 100.0;
}
function getPreviousGames() {
const previousGames = [];
let gameHash = generateHash(crashHash);
for (let i = 0; i < 100; i++) {
const gameResult = crashPointFromHash(gameHash);
previousGames.push({ gameHash, gameResult });
gameHash = generateHash(gameHash);
}
return previousGames;
}
function verifyCrash() {
const gameResult = crashPointFromHash(crashHash);
const previousHundredGames = getPreviousGames();
return { gameResult, previousHundredGames };
}
console.log(verifyCrash());
Code Sandbox
I'm trying to make this code show the results it already shows, but I want it to add something to the end of each gameResult data so it would look like this: gameResult: 4.39 "maybe"
I've tried to add something like this to the code with no luck. I had it working to the point where it would only return the very first gameResult but not the ones after. If someone could help that would be great, or if you have another way other than this code below that I was trying to use, that works too.
function gameResult
const result =
if (gameResult === 1) {
return "no";
};
if (gameResult <= 3) {
return "maybe";
};
if (gameResult <= 10) {
return "yes";
};
So, if I understand correctly the expected output should be like this,
{
"gameResult": "4.39 "yes"",
"previousHundredGames": [...]
}
I am able to do this by modifying the verifyCrash function to this,
function verifyCrash() {
let gameResult = crashPointFromHash(crashHash);
const previousHundredGames = getPreviousGames();
if (gameResult === 1) {
gameResult=+' "no"';
}
if (gameResult <= 3) {
gameResult=+' "maybe"';
}
if (gameResult <= 10) {
gameResult+= ' "yes"';
}
return { gameResult, previousHundredGames };
}
Check this link to see it in action,
https://codesandbox.io/s/crash-forked-f7fb7

Node require 3rd party script

I need to get my google one-time password every time when I receive a new one.
Please check here also.
I want to use this code inside my app.js (in server side java script file). I have been trying to figure it out but could't make it.
I copied and pasted to all code in that website and created at under same directory and required it.
I tried this:
myKey = '**my_key_is_here';
require('./sha.js');
function dec2hex(s) { return (s < 15.5 ? '0' : '') + Math.round(s).toString(16); }
function hex2dec(s) { return parseInt(s, 16); }
function base32tohex(base32) {
var base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
var bits = "";
var hex = "";
for (var i = 0; i < base32.length; i++) {
var val = base32chars.indexOf(base32.charAt(i).toUpperCase());
bits += leftpad(val.toString(2), 5, '0');
}
for (var i = 0; i + 4 <= bits.length; i += 4) {
var chunk = bits.substr(i, 4);
hex = hex + parseInt(chunk, 2).toString(16);
}
return hex;
}
function leftpad(str, len, pad) {
if (len + 1 >= str.length) {
str = Array(len + 1 - str.length).join(pad) + str;
}
return str;
}
function updateOtp() {
var key = base32tohex(myKey);
var epoch = Math.round(new Date().getTime() / 1000.0);
var time = leftpad(dec2hex(Math.floor(epoch / 30)), 16, '0');
// updated for jsSHA v2.0.0 - http://caligatio.github.io/jsSHA/
var shaObj = new jsSHA("SHA-1", "HEX");
shaObj.setHMACKey(key, "HEX");
shaObj.update(time);
var hmac = shaObj.getHMAC("HEX");
if (hmac == 'KEY MUST BE IN BYTE INCREMENTS') {
console.log('something wrong with HMAC');
} else {
var offset = hex2dec(hmac.substring(hmac.length - 1));
var part1 = hmac.substr(0, offset * 2);
var part2 = hmac.substr(offset * 2, 8);
var part3 = hmac.substr(offset * 2 + 8, hmac.length - offset);
}
var otp = (hex2dec(hmac.substr(offset * 2, 8)) & hex2dec('7fffffff')) + '';
otp = (otp).substr(otp.length - 6, 6);
var test = otp;
console.log(test);
}
function timer() {
var epoch = Math.round(new Date().getTime() / 1000.0);
var countDown = 30 - (epoch % 30);
if (epoch % 30 == 0) updateOtp();
// $('#updatingIn').text(countDown);
}
function startFactor() {
updateOtp();
setInterval(timer, 1000);
};
startFactor();
but getting this output :
ReferenceError: jsSHA is not defined
Basic Question is: How can I use this file in my Nodejs project.
Install it from npm repo:
npm install jssha --save or npm install jssha --save-dev
and then require:
jsSHA = require("jssha");
It was so simple to do with speakeasy !
That was what I needed.
Solved.

JavaScript prototype password generator

I wrote a simple JS script to generate a random password.
My code that work now but with just small letters
function Password(l) {
this.l = l;
}
Password.prototype.generate = function () {
var p = "";
for (let i=0; i < this.l; i++) {
p = p + String.fromCharCode(Math.floor(Math.random() * (122 - 97 + 1) + 97));
}
return p;
};
p = new Password(8);
console.log(p.generate());
For finding a char code
console.log("A".charCodeAt(0));
console.log("Z".charCodeAt(0));
console.log("0".charCodeAt(0));
console.log("9".charCodeAt(0));
One of my idea for get this done but I don't know how ?
if (Math.random() < .5) {
console.log("OK");
} else {
console.log("NOT OK");
}
console.log(Math.random());
Thanks in advance for this
And if some of write code it's better to understand
Update 1 : Someone complete the code with new features means Capital letters and add numbers to it with shuffle.

How would you throttle a recursive function?

Let's suppose I want to run a recursive function that will take weeks, months or even years to complete. It returns all possible permutations of a string based on the specified parameters. While it's running, I want to be able to see how far along it is progressing - e.g. how many permutations it has generated so far. In a nutshell, I want a very long-running recursive function to execute without locking up my UI.
Also, I would like to do this with vanilla ES5, not in strict mode, and without WebWorkers. It should be able to run in IE9.
What I have works fine as-is, but when I raise numspaces to 10, for example, the browser locks up. So I am assuming that I am just working the browser too hard, and "throttling" the amount of work it has to do would help solve this problem. I did try increasing the setTimeout delays from 1 to 250 and even 1000, but the browser still locked up.
I am interested in this simply because I tried to do it, and couldn't. Also, I know for a fact that this code is terribly inefficient and there are much, much better ways to do what I am looking to achieve. So recommend them!
var inputString = "abcdefghijklmnopqrstuvwxyz";
function allPossibleCombinations(input, length, curstr, callback) {
if (curstr.length === length) return callback(curstr);
(function(n) {
setTimeout(allPossibleCombinations.bind(n, input, length, curstr + input[n], callback), 1);
n++;
if (n < input.length) setTimeout(arguments.callee.bind(n,n), 1);
})(0);
}
var totalResults = 0,
numDigits = inputString.length,
numSpaces = 2,
maxResults = Math.pow(numDigits, numSpaces),
consoleElement = document.getElementById('console'),
startTime = +new Date();
console.log("Starting.. expecting", maxResults, "total results...");
allPossibleCombinations(inputString.split(""), numSpaces, "", function(result) {
totalResults++;
if (totalResults === maxResults) {
var elapsed = +new Date() - startTime;
consoleElement.innerText = "Done.";
console.log("Completed in", elapsed, "ms!");
} else {
// Do something with this permutation...
//...
// Show progress...
var progress = ((totalResults / maxResults) * 100).toFixed(2) * 1;
consoleElement.innerText = progress + "%";
}
});
<div id="console"></div>
You’re getting close with the setTimeout, but the current implementation queues up all the timers for a given prefix at once, resulting in an exponential number of timers and quick memory exhaustion. One small change would be to create another callback to indicate completion and use it to wait on recursive calls, never holding more than one timer at once:
var inputString = "abcdefghijklmnopqrstuvwxyz";
function allPossibleCombinations(input, length, curstr, resultCallback, doneCallback) {
if (curstr.length === length) {
resultCallback(curstr);
doneCallback();
return;
}
var n = 0;
(function next() {
if (n === input.length) {
doneCallback();
return;
}
allPossibleCombinations(
input, length, curstr + input[n],
resultCallback,
function () {
n++;
setTimeout(next, 0);
});
})();
}
var totalResults = 0,
numDigits = inputString.length,
numSpaces = 4,
maxResults = Math.pow(numDigits, numSpaces),
consoleElement = document.getElementById('console'),
startTime = +new Date();
console.log("Starting.. expecting", maxResults, "total results...");
allPossibleCombinations(
inputString.split(""), numSpaces, "",
function (result) {
totalResults++;
// Do something with this permutation...
//...
// Show progress...
var progress = ((totalResults / maxResults) * 100).toFixed(2) * 1;
consoleElement.innerText = progress + "%";
},
function () {
var elapsed = +new Date() - startTime;
consoleElement.innerText = "Done.";
console.log("Completed in", elapsed, "ms!");
});
<div id="console"></div>
That’s really slow, though. Thinking of how you could write this as a generator:
function* strings(input, length, current) {
if (current.length === length) {
yield current;
return;
}
for (let i = 0; i < input.length; i++) {
yield* strings(input, length, current + input[i]);
}
}
and translating that to a system where the callback is responsible for resuming generation:
function strings(input, length, current, yield_, continue_) {
if (current.length === length) {
yield_(current, continue_);
return;
}
var i = 0;
(function next() {
if (i === input.length) {
continue_();
return;
}
strings(input, length, current + input[i++], yield_, next);
})();
}
you can have the flexibility of setting a timer as infrequently as you’d like for performance.
"use strict";
function countSequences(n, k) {
var result = 1;
for (var i = 0; i < k; i++) {
result *= n--;
}
return result;
}
function strings(input, length, current, yield_, continue_) {
if (current.length === length) {
yield_(current, continue_);
return;
}
var i = 0;
(function next() {
if (i === input.length) {
continue_();
return;
}
var c = input[i++];
strings(input.replace(c, ''), length, current + c, yield_, next);
})();
}
var inputString = "abcdefghijklmnopqrstuvwxyz";
var totalResults = 0;
var numDigits = inputString.length;
var numSpaces = 5;
var maxResults = countSequences(numDigits, numSpaces);
var consoleElement = document.getElementById('console');
var startTime = +new Date();
console.log("Starting… expecting", maxResults, "total results.");
strings(
inputString, numSpaces, "",
function (result, continue_) {
if (totalResults++ % 1000 === 0) {
var progress = (totalResults / maxResults * 100).toFixed(2);
consoleElement.innerText = progress + "% (" + result + ")";
setTimeout(continue_, 0);
} else {
continue_();
}
},
function () {
var elapsed = +new Date() - startTime;
consoleElement.innerText = "Done.";
console.log("Completed in", elapsed, "ms!");
});
<div id="console"></div>
(This style is still non-optimal, but it’ll never finish for 2610 no matter how quick individual operations are.)

Calculate unique time given multiple start and end dates

If you have an array of appointments with start and end dates how do you calculate the unique time for all of the appointments?
Example:
var appointments = {
0:{"start":"2015-01-20 09:00:00","end":"2015-01-20 09:30:00"},
1:{"start":"2015-01-20 09:15:00","end":"2015-01-20 09:42:22"},
2:{"start":"2015-01-20 10:00:00","end":"2015-01-20 10:25:00"},
3:{"start":"2015-01-20 10:10:00","end":"2015-01-20 10:53:00"}
}
So in this example I would want to get a unique time (activity) value of 1H 35M 22S.
Anyone know any formulas for this?
So far I have this, seems to work but I think dates have to be sorted by start time. Is this the most efficient way to calculate this?:
var totalElapsedAppointmentSeconds = 0;
var lastActiveTimestamp;
for (i in appointments) {
if (totalElapsedAppointmentSeconds == 0) {
totalElapsedAppointmentSeconds = new Date(appointments[i].end) - new Date(appointments[i].start);
lastActiveTimestamp = new Date(appointments[i].end);
} else {
if (new Date(appointments[i].start) < lastActiveTimestamp) {
if (new Date(appointments[i].end) > lastActiveTimestamp) {
totalElapsedAppointmentSeconds += new Date(appointments[i].end) - lastActiveTimestamp;
lastActiveTimestamp = new Date(appointments[i].end);
} else {
//nothing, already completely accounted for
}
} else {
totalElapsedAppointmentSeconds += new Date(appointments[i].end) - new Date(appointments[i].start);
lastActiveTimestamp = new Date(appointments[i].end);
}
}
}
totalElapsedAppointmentSeconds = totalElapsedAppointmentSeconds/1000;
var totalElapsedTime = Math.floor(totalElapsedAppointmentSeconds / 3600) + "H " + Math.floor((totalElapsedAppointmentSeconds % 3600)/60) + "M " + (totalElapsedAppointmentSeconds % 3600) % 60 + "S";
console.log("totalElapsedTime",totalElapsedTime);
unclear what you are asking but this demonstrates calculating a time difference
EDIT whoops javascript says these are invalid dates, where did they come from?
moment.js is a good option to parse them if you must use these as inputs
var data = {
"appointments": {
0:{"start":"2015-01-20 09:00:00","end":"2015-01-20 09:30:00"},
1:{"start":"20-01-2015 09:15:00","end":"20-01-2015 09:42:22"},
2:{"start":"20-01-2015 10:00:00","end":"20-01-2015 10:25:00"},
3:{"start":"20-01-2015 10:10:00","end":"20-01-2015 10:53:00"},
}
}
function secondsDifference(ts1, ts2){
startMs = new Date(ts1).valueOf();
endMs = new Date(ts2).valueOf();
deltaMs = endMs - startMs;
deltaS = deltaMs /1000;
deltaS = Math.floor(deltaS);
return deltaS;
}
var a = data.appointments[0];
var result = secondsDifference(a.start, a.end);
console.log('first appointment length seconds:', result)

Categories