How would I stop receiving a new RandomNumber within this code? [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 days ago.
Improve this question
I am trying to encode a string of words the user gives using ASCII. Doing it by each character. But the random number keeps changing insetead of using the same number to encode.
I want all the Uppercase letters to be the same number/character.
const rand = generateRandom(65, 90);
const randomNum = rand;
function generateRandom(min, max)
{
let rand = Math.floor(Math.random() * (max - min) + 1) + min;
return rand;
}
function encodeIt()
{
document.getElementById("message").innerHTML = ("<h2> </h2>");
var msg = prompt("Enter your message." , " ");
let newmsg = " ";
var upCaseCode = 155;
var newCode = 0;
var lowCaseCode = 219;
var specialCode = 3;
//the loop encodes each letter in the message string
for (var j = 0; j < msg.length; j++)
{
//check for lowercase letters and encode them
if ((msg.charCodeAt(j)>=97) && (msg.charCodeAt(j)<=122))
{
newcode = (lowCaseCode - msg.charCodeAt(j));
}
else
//check for numbers and special characters and encode them33.
if (((msg.charCodeAt(j)>90) && (msg.charCodeAt(j)<97)) || (msg.charCodeAt(j)<65))
{
newcode = (msg.charCodeAt(j) + specialCode);
}
//add each encoded character to the new message
newmsg = newmsg + " " + String.fromCharCode(newcode);
}
//display the encoded message on the web page
document.getElementById("secret").innerHTML = ("<h2>" + newmsg + "</h2>");
//decide if original message should be shown
var choice = prompt("Do you want the special key? Yes or No?", " ");
if ((choice.charAt(0) == 'y') || (choice.charAt(0) == 'Y'))
{
document.getElementById("message").innerHTML = ("<h2>" + randomNum + "</h2>");
}
}
//check for upppercase letters and encode them
if ((msg.charCodeAt(j)>=65) && (msg.charCodeAt(j)<=90))
{
newcode = (**randomNum **- msg.charCodeAt(j));
}
else

Related

Javascript median using for

So I'm trying to learn javascript, and I want to find the median of some numbers that I insert into a prompt when I click on the button "find median".
function Media()
{
var n = prompt("number of elements?");
var i = 1;
var s = 0;
for (i=1;i<=n;i++)
{
var m = prompt("insert # " +i);
s = s+m;
}
var media = s/n;
document.getElementById("rezultat").innerHTML = "result: " +media
}
I made a test with two numbers, 1 and 2, and the median was 6, and i cant figure what i've done wrong
You should parse the result of prompt to an integer;
How to convert a string to an integer in JavaScript?
function Media() {
var n = parseInt(prompt("number of elements?"));
var i = 1;
var s = 0;
for (i=1;i<=n;i++)
{
var m = prompt("insert # " +i);
m = parseInt(m);
s = s+m;
}
var media = s/n;
document.getElementById("rezultat").innerHTML = "result: " +media
}
Media();
<div id='rezultat' />
You should also parse the result of prompt using parseInt
var m = parseInt(prompt("insert # " + i));
s/n gives the mean of the input. If you are looking for the median, you should use an array to store the inputs and get the element(s) in the middle.

Random password generator with prompts [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm working on an assignment that requires prompts asking for password length and character type and I have two issues:
a) The prompts aren't showing up
b) I cant seem to put the password in my display box. Here is my code:
var length = Number(prompt("How many characters will your password be? Enter a number between 8 and 128"));
//ask for character type
var charType = prompt("Enter a character type: special, numeric, uppercase, lowercase.");
//generate password
function generatePassword() {
//evaluate character type
var charSet = "";
var charTypeLower = charType.toLowerCase();
if (charTypeLower === "lowercase") {
charSet = "abcdefghijklmnopqrstuvwxyz";
} else if (charTypeLower === "uppercase") {
charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
} else if (charTypeLower === "numeric") {
charSet = "0123456789";
} else if (charTypeLower === "special") {
charSet = " !\"#$%&'()*+,-./:;<=>?#[\]^_`{|}~";
}
//return value
var retVal = "";
for (var i = 0; i < length; i++) {
//picks a character within charSet at index of random number
retVal += charSet.charAt(Math.floor(Math.random() * charSet.length));
}
return retVal;
}
alert(generatePassword());
}
//make password appear in display box
document.getElementById("display").value = password;
//function to copy password to clipboard
function copyPassword() {
document.getElementById("display").select();
document.execCommand("Copy");
alert("Password copied to clipboard!");
You had a } after your alert, which was throwing an error and preventing the prompts from showing. I applied some other fixes as well:
var length = Number(prompt("Enter a password length between 8 and 128")),
charType = prompt("Enter a character type: special, numeric, uppercase, lowercase."),
password = generatePassword();
document.getElementById("display").value = password;
document.getElementById('copy-btn').addEventListener('click', copyPassword);
function generatePassword() {
var charSets = {
lowercase: 'abcdefghijklmnopqrstuvwxyz',
uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
numeric: '0123456789',
special: ' !"#$%&\'()*+,-./:;<=>?#[\\]^_`{|}~'
};
var charSet = charSets[charType.toLowerCase()] || charSets.lowercase;
var retVal = "";
for (var i = 0; i < length; i++) {
retVal += charSet.charAt(Math.floor(Math.random() * charSet.length));
}
return retVal;
}
function copyPassword() {
document.getElementById("display").select();
document.execCommand("Copy");
alert("Password copied to clipboard!");
}
<input id="display"> <button id="copy-btn">Copy</button>

Can't convert string to number

I have a large text from which I read data according to the scheme. Key words are placed in the "smallArtName" array. The scheme looks like this:
(key word) xxx (cordX|cordY)
I can't convert the string I received to a number. It seems to me that the reason is white space, visible in the terminal in the picture. I tried to use the replace method which works for sample text, but not for my value.
I'm a beginner and I could probably do it simpler, but the code I wrote works, and this is the most important thing for now.
for (i = 0; i < smallArtName.length; i++) {
var n = art.artPrintScreen.indexOf(smallArtName[i]);
if (n > 0) {
var tempString = art.artPrintScreen.substring(n, n + 100);
betweenChar = tempString.indexOf('|');
for (k = betweenChar - 10; k <= betweenChar + 10; k++) {
if (tempString[k] == '(') {
xStart = k;
}
if (tempString[k] == ')') {
yEnd = k;
}
}
cordX = tempString.slice(xStart + 1, betweenChar);
cordY = tempString.slice(betweenChar + 1, yEnd);
strTest = " t est".replace(/\s/g, '')
var cordY2 = cordY.replace(/\s/g, '')
console.log(typeof (cordY))
console.log(cordY2)
console.log(cordY2[0])
console.log(cordY2[1])
console.log(cordY2[2])
console.log(cordY2[3])
console.log(cordY2[4])
console.log(cordY2[5])
console.log(strTest)
var cordYtest = parseInt(cordY2, 10);
console.log(cordYtest)
}
}
You just need to change the regex so that you replace everything except digits and the negative sign - rather than just whitespace. i.e.
change
var cordY2 = cordY.replace(/\s/g, '')
to
var cordY2 = parseInt(cordY.replace(/[^0-9-]/g, ''), 10);
So that the variable cordY2 contains the number you require.

Java script written for UUID is not working in jmeter

Find below the code we have developed in java script to run in jmeter using JSR223 sampler(running as a java script). The same code worked on Jquery when developed but not posting the id while running in jmeter. the error thrown is "appid" is not defined. Could someone help debugging the issue looking at the code
vars.put("guid", "${__UUID}"); 
vars.put("appId", "ce547c40-acf9-11e6-80f5-76304dec7eb7");
var id=getAppInfo(appId, guid);
function getAppInfo(appId, guid)
{
var appInfo = null;
var appIdBytes = guidToBytes(appId);
var guidBytes = guidToBytes(guid);
var appInfoBytes = [];
for (var cnt = 0; cnt < appIdBytes.length; cnt++)
{
appInfoBytes[cnt] = appIdBytes[cnt] + guidBytes[cnt];
}
var appInfoGuidfromBytes = bytesToGuid(appInfoBytes);
return appInfoGuidfromBytes;
}
function bytesToGuid(guidBytes) {
var x = guidBytes;
var result = "";
var bytes = x.slice(0, 4).reverse().concat(x.slice(4, 6).reverse()).concat(x.slice(6, 8).reverse()).concat(x.slice(8));
var y = bytes.map(function (item) { return ('00' + item.toString(16)).substr(-2, 2) });
var byteArray = y;
for (var cnt = 0; cnt < byteArray.length; cnt++) {
if (cnt === 4 || cnt === 6 || cnt === 8 || cnt === 10)
result = result + "-" + byteArray[cnt];
else
result = result + byteArray[cnt];
}
return result;
}
function guidToBytes(guid) {
var bytes = [];
guid.split('-').map(function (number, index) {
var bytesInChar = index < 3 ? number.match(/.{1,2}/g).reverse() : number.match(/.{1,2}/g);
bytesInChar.map(function (byte) { bytes.push(parseInt(byte, 16)); });
});
return bytes;
}
// Create the Randon Number. It will call from NewGuid function.
function getRandomNumber() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};
// Creating GUID eg. "cbe26df8-2b01-4377-9ae8-1d023ccd5171"
// getRandomNumber returns 4 digit Alphanumeric number and we are going to concatenating this with "-" symbol and third number starts with "-4" and substring the random number and concatenate the string and return.
function newGuid() {
return (getRandomNumber() + getRandomNumber() + "-" + getRandomNumber() + "-4" + getRandomNumber().substr(0, 3) + "-" + getRandomNumber() + "-" + getRandomNumber() + getRandomNumber() + getRandomNumber()).toLowerCase();
};
You shouldn't call JMeter's function inside JSR223 script.
Instead, add it to Parameters field as ${__UUID}
and then use it using args:
vars.put("guid", args[0]);
args - the parameters as a String array (split on whitespace)

JavaScript Calculator - scope?

I am relatively new to JS, and trying to create a JavaScript calculator that takes a number and then uses the operator with a second number to create a total. Then I could use another operator on that total with another number, and so on, until the clear button is pressed. My biggest problem seems to be with the scope of my variables. At the moment I created a stopgap, that will add and subtract one digit numbers. Is there a reason why this code won't at least multiply and divide single numbers?
My other idea is to create two variables with empty arrays for the two numbers that will be used, so that as each active button is pressed you can push it into the specific array, which I think would solve the problem of only using single digit numbers, right? Thanks in advance! Just trying to learn and keep getting better!
// Calculator
var number = '';
var newNumber = '';
var operator = '';
var totalVal = '';
var result = '';
var inputCount = 0;
// Adds clicked numbers to the number variable and then sets value to totalVal
$('.numbers').on('click', function(){
if(result == ''){
inputCount++;
if (inputCount < 2){
number += $(this).text();
$('.inner-screen').text(number);
result = number;
console.log("number: " + number);
console.log("result: " + result);
} else {
newNumber = $(this).text();
}
// number = '';
} else{
newNumber += $(this).text();
$('.inner-screen').text(newNumber);
}
console.log("number: " + number + ", newNumber: " + newNumber);
});
$('.operators').on('click', function(){
operator = $(this).text();
console.log(operator);
$('.inner-screen').text('');
});
// Resets all the variables when clear button is clicked
$('.clear').on('click', function(){
number = '';
result = '';
newNumber = '';
operator = '';
totalVal = '';
inputCount = 0;
console.log('Clear Button Worked!');
$('.inner-screen').text('');
});
$('.eval').on('click', function(){
console.log("num1: " + number + ", operator: " + operator + ", num2: " + newNumber);
if (operator === " + "){
result = parseFloat(newNumber) + parseFloat(number);
console.log(result);
} else if (operator === " - "){
result = parseFloat(number) - parseFloat(newNumber);
console.log(totalVal);
} else if (operator === " X "){
result = parseFloat(newNumber) * parseFloat(number);
console.log(result);
} else if (operator === " / "){
result = parseFloat(number) / parseFloat(newNumber);
console.log(result);
} else {
console.log("didn't catch");
}
$('.inner-screen').text(result);
number = '';
newNumber = '';
});
Is there a reason why this code won't at least multiply and divide single numbers?
Right-o. I see what's going on.
Once you've pressed eval, you need to remember some state:
number = result;
result = '';
newNumber = '';
operator = '';
inputCount = 1;
Old version:
http://jsfiddle.net/xjegrp58/
New version, with state added to the eval function:
http://jsfiddle.net/axLhcawf/
Try this on each:
2 * 2 = 4, then * 2 to get 8

Categories