Function return multiple value - javascript

I have this modified code here, how do I pass the argument?
function RNG(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function RCG() {
var char = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
var randomNumber = RNG(0, char.length - 1);
return char[randomNumber];
}
function Generator(n) {
var serialNumber;
var template = "0000-0000-0000-0000";
if (template != null) {
for (var i = 0; i < template.length; i++) {
var templateChar = template[i];
serialNumber += templateChar == "0" ? RCG() : templateChar;
}
}
return serialNumber;
}
console.log(Generator(5));
So when I enter 3 as the argument, the result will be like:
asda-asda-asda-asda
asda-asda-asda-asda
asda-asda-asda-asda

I think what you are asking is to be able to return 5 of these UUID from your method?
I have modified your Generator to return an array of UUIDs
function Generator(n) {
var template = "0000-0000-0000-0000";
var res = []; // declare an empty array
if (template != null) {
for (var j = 0; j < n; j++){
var serialNumber = "";
for (var i = 0; i < template.length; i++) {
var templateChar = template[i];
serialNumber += templateChar == "0" ? RCG() : templateChar;
}
res.push(serialNumber); // add uuid in the array
}
}
return res; // return the array
}
Output:
["1MYK-G2BB-YPG4-UYHU", "PWW1-6297-2VJX-56F2", "5U5B-A40D-9V43-WC6Y", "FQHQ-BU6A-CDS8-Y2J7", "23WK-1ASP-YA5Z-TS0R"]

Related

I'm trying to make this code in vanilla javascript work in reactjs, but it's falling into the infinite loop

This is the code i got from codepen, it generates special characters and changes to the phrase i put, I'm wanting to compile this vanilla javascript code to react, because you can't use the DOM
there.
My real doubt is where do I put the useState so that it stops looping and shows character by character, this passing for example the state 'title' in a .
vanilla javascript code:
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-=+<>,./?[{()}]!##$%^&*~`\|'.split('');
var progress404 = 0;
var total404 = $('.text__error').data('text').length;
var progressLink = 0;
var totalLink = $('.text__link a').data('text').length;
var scrambleInterval = setInterval(function() {
var string404 = $('.text__error').data('text');
var stringLink = $('.text__link a').data('text');
for(var i = 0; i < total404; i++) {
if(i >= progress404) {
string404 = setCharAt(string404, i, characters[Math.round(Math.random() * (characters.length - 1))]);
}
}
for(var i = 0; i < totalLink; i++) {
if(i >= progressLink) {
stringLink = setCharAt(stringLink, i, characters[Math.round(Math.random() * (characters.length - 1))]);
}
}
$('.text__error').text(string404);
$('.text__link a').text(stringLink);
}, 1000 / 60);
setTimeout(function() {
var revealInterval = setInterval(function() {
if(progress404 < total404) {
progress404++;
}else if(progressLink < totalLink) {
progressLink++;
}else{
clearInterval(revealInterval);
clearInterval(scrambleInterval);
}
}, 50);
}, 1000);
This is the code I developed to try to work:
const [ title, setTitle ] = useState('404 page not found')
const [ link, setLink ] = useState('click here to go home')
function setCharAt(str: string,index: number,chr: any) {
if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-=+<>,./?[{()}]!##$%^&*~`\|'.split('');
var progress404 = 0;
var total404 = title.length
var progressLink = 0;
var totalLink = link.length
var scrambleInterval = setInterval(function() {
for(var i = 0; i < total404; i++) {
if(i >= progress404) {
setTitle( setCharAt(title, i, characters[Math.round(Math.random() * (characters.length - 1))]));
}
}
for(var i = 0; i < totalLink; i++) {
if(i >= progressLink) {
setLink( setCharAt(link, i, characters[Math.round(Math.random() * (characters.length - 1))]));
}
}
}, 1000 / 60);
setTimeout(function() {
var revealInterval = setInterval(function() {
if(progress404 < total404) {
progress404++;
}else if(progressLink < totalLink) {
progressLink++;
}else{
clearInterval(revealInterval);
clearInterval(scrambleInterval);
}
}, 50);
}, 1000);

How to create n different arrays with 6 random numbers each. - Javascript/Jquery

I want to create 1 - 12 arrays of 6 random numbers each.
At the moment I can only create one. So I don't know how to loop this.
This is my code so far:
<script type="text/javascript">
function schleife() {
var arr = [];
var krams = [];
for(i=1; i<=6; i++) {
var zufall = Math.floor((Math.random() * 49) + 1);
krams.push(zufall++);
}
arr.push(krams.toString() + "<br /><br />");
$(".bsp2").append(arr);
}
function uebertrag() {
schleife();
}
</script>
You need to create new function: e.g. getArrayOfRandomNumbers
function getArrayOfRandomNumbers() {
var krams = []
for(var i=1; i<=6; i++) {
var zufall = Math.floor((Math.random() * 49) + 1)
krams.push(zufall++)
}
return krams
}
And now you can invoke this function in loop:
for (var j = 0; j < 12; j++) {
var arrayOfRandomNumber = getArrayOfRandomNumbers()
//do something with this array, e.g. append
$(".bsp2").append(arrayOfRandomNumber.toString())
}
function schleife(iRange, jRange) {
var array = []
for (i = 1; i <= iRange; i++) {
var krams = [];
for(j = 1; j <= jRange; j++) {
var zufall = Math.floor((Math.random() * 49) + 1);
krams.push(zufall++);
}
array.push(krams);
$(".bsp2").append(krams + "<br /><br />");
}
return array;
}
schleife(12, 6);
Thank you havenchyk. I was able to make it with your code!
Great! I'm really happy up to this point. ;-)
That's how it looks now:
function getArrayOfRandomNumbers() {
var krams = [];
while(krams.length < 6) {
var zufall = Math.floor((Math.random() * 49) + 1);
var found = false;
for(var i=0; i<krams.length; i++) {
if(krams[i] == zufall) {
found = true;
break
}
}
if(!found){
krams.push(zufall++);
}
}
return krams;
}
function getArrays() {
function compareNumbers(a, b) {
return a - b;
}
var results = [];
for (var j = 0; j <= 10; j++) {
var arrayOfRandomNumber = getArrayOfRandomNumbers();
//do something with this array
results.push(arrayOfRandomNumber.splice(0, 6).sort(compareNumbers).toString()+"<br /><br />");
}
$(".bsp2").append(results[1]);
$(".bsp2").append(results[2]);
$(".bsp2").append(results[3]);
$(".bsp2").append(results[4]);
$(".bsp2").append(results[5]);
$(".bsp2").append(results[6]);
$(".bsp2").append(results[7]);
$(".bsp2").append(results[8]);
$(".bsp2").append(results[9]);
$(".bsp2").append(results[10]);
}

how do i get non-repeated character and its count in JavaScript?

Here is my code. What should I modify of this code to get the output as
"T-1
r-1
a-1
e-1 "
(other characters are repeating. So no need to print the others)
function different() {
var retureArr = [];
var count = 0;
var complete_name = "Trammell";
var stringLength = complete_name.length;
for (var t = 0; t < stringLength; t++) {
for (var s = 0; s < stringLength; s++) {
var com1 = complete_name.charAt(t);
var com2 = complete_name.charAt(s);
if (com1 != com2) {
retureArr[count] = com1;
count++;
}
}
count = 0;
}
}
I think this is what you want. You need to count the number of occurrences of each character in a dictionary. Then you can print them based on the count being equal to 1.
var retureArr = [];
var complete_name = "Trammell";
for (var i = 0; i < complete_name.length; i++)
{
var key = complete_name[i];
if (!(key in retureArr))
{
retureArr[key] = 1;
}
else
{
retureArr[key] = retureArr[key] + 1;
}
}
var output = "";
for (var key in retureArr)
{
if (retureArr[key] == 1)
{
output += key + "-" + retureArr[key] + " ";
}
}
alert(output);
This alerts the following string:
T-1 r-1 a-1 e-1
This works. but perhaps isn't the most efficient!
var string = "input string";
var stringList = [];
var outputString = "";
for (var i=0; i < string.length; i++){
var charObject = {"Char": string.charAt(i), "Passed": false};
stringList.push(charObject);
}
for (var i=0; i < stringList.length; i++){
if(!stringList[i].Passed && stringList[i].Char != " "){
var currentCount = countOccurrences(string, stringList[i].Char);
if(currentCount == 1){
outputString += stringList[i].Char+"-"+currentCount + " ";
}
stringList[i].Passed = true;
}
}
console.log(outputString);
function countOccurrences(string, char){
var count = 0;
for (var i=0; i < string.length; i++){
if(string.charAt(i) == char){
count++;
}
}
return count;
}

Protractor:How to store values in array and then to do sorting

I need to sort list strings under the table ,so for that i have written following lines of code but on console i am not getting any values:
var j = 9;
var rows = element.all(by.repeater('row in renderedRows'));
var column = element.all(by.repeater('col in renderedColumns'));
expect(rows.count()).toEqual(5); //here its printing number of rows
expect(column.count()).toEqual(5); //here its printing number of columns
var arr = [rows.count()];
for (var i = 0; i < rows.count(); i++) {
console.log("aai" + i);
if (i = 0) {
//var columnvalue=column.get(9).getText();
var columnvalue = column.get(9).getText().then(function(ss) {
return ss.trim();
arr[i] = ss.trim(); //here it will save the value first value of column
console.log("value1" + arr[i]);
expect(arr[i]).toEqual('DN');
console.log("aa" + ss.trim());
});
} else {
var j = j + 8;
var columnvalue = column.get(j).getText().then(function(ss) {
return ss.trim();
arr[i] = ss.trim(); //here it will save the other values of column
console.log("value" + arr[i]);
expect(arr[i]).toEqual('DN');
console.log("ab" + ss.trim());
});
}
}
Sorting_Under_Table: function(col){
test = [];
var m;
var dm = 0;
element(by.xpath('//div[#class="ngHeaderScroller"]/div['+col+']')).click();
element.all(by.repeater('row in renderedRows')).then(function(row) {
m = row.length;
for (i = 1; i <= row.length; i++)
{
user_admin_table_name = browser.driver.findElement(by.xpath('//div[#class="ngCanvas"]/div['+i+']/div['+col+']'));
user_admin_table_name.getText().then(function(text) {
var test_var1 = text.toLowerCase().trim();
test.push(test_var1);
var k = test.length
if (k == m){
for (j = 0; j < test.length; j++){
test.sort();
d=j+1;
user_admin_table_name1 = browser.driver.findElement(by.xpath('//div[#class="ngCanvas"]/div['+d+']/div['+col+']'));
user_admin_table_name1.getText().then(function(text1) {
var test_var2 = text1.toLowerCase().trim();
if (test_var2 == test[dm]){
expect(test_var2).toEqual(test[dm]);
dm = dm +1;
}else {
expect(test_var2).toEqual(test[dm]);
log.error("Sorting is not successful");
dm = dm +1;
}
});
}
}
});
}
});
},
You can use this code for sorting and verifying is it sorted or not
I'm not sure how your above example is doing any sorting, but here's a general solution for trimming and then sorting:
var elementsWithTextToSort = element.all(by.xyz...);
elementsWithTextToSort.map(function(elem) {
return elem.getText().then(function(text) {
return text.trim();
});
}).then(function(trimmedTexts) {
return trimmedTexts.sort();
}).then(function(sortedTrimmedTexts) {
//do something with the sorted trimmed texts
});

Sum ranged values

I am trying to sum the ranged values but for some reason it's not summing. Any idea why?
I am not a very good in JavaScript but I have some knowledge...
function bag(input) {
var sheet = SpreadsheetApp.getActiveSpreadsheet()
var AllValues = sheet.getRange(input).getValues();
var FValue = "";
var TotalGold = 0;
var TotalSilver = 0;
var TotalBronze = 0;
for(i = 0; i < AllValues.length; i++) {
var total = AllValues[i][0].split(" ");
for(i = 0; i < total.length; i++){
if (total[i].indexOf("g") >= 0) {
var value = total[i].replace("g","");
var gold = value * 1;
TotalGold = TotalGold + gold;
}
else if (total[i].indexOf("s") >= 0) {
var value = total[i].replace("s","");
var silver = value * 1;
TotalSilver = TotalSilver + silver;
}
else if (total[i].indexOf("b") >= 0) {
var value = total[i].replace("b","");
var bronze = value * 1;
TotalBronze = TotalBronze + bronze;
}
else {
return null;
}
}
}
return TotalGold + "g " + TotalSilver + "s " + TotalBronze + "b";
}
It appears you are overwriting your value of i in the nested iteration. Pick another identifier. E.g: for (var j = 0; j < total.length; j++) { ... }

Categories

Resources