JavaScript - How to increase count - javascript

when I give the variable which is an IP(10.31.68.0/22) with the current below script it will return
Output: 10.31.68.1 - 10.31.68.10
var network = '10.31.68.0/22';
var IPstart = network.toString().substring(0,network.lastIndexOf('.')) + ".1";
var IPend = network.toString().substring(0,network.lastIndexOf('.')) + ".10";
var excludename = IPstart+"-"+IPend;
I am looking for something (Output) like below. 68 placeholder should increase by +1 like below.
10.31.68.1 - 10.31.68.10
10.31.69.1 - 10.31.69.10
10.31.70.1 - 10.31.70.10
10.31.71.1 - 10.31.71.10

You Need to split and join the values with loop
var network = '10.31.68.0/22';
var IPstart = network.toString().substring(0,network.lastIndexOf('.')) + ".1";
var IPend = network.toString().substring(0,network.lastIndexOf('.')) + ".10";
var excludename = IPstart+"-"+IPend;
var upToNumber=4;
for(var i=0;i<upToNumber;i++){
var res_ipstart = IPstart.split(".");
res_ipstart[2]=parseInt(res_ipstart[2]) + i;
var ip_start = res_ipstart.join(".");
var res_ipend = IPend.split(".");
res_ipend[2]=parseInt(res_ipend[2]) + i;
var ip_end = res_ipend.join(".");
var output=ip_start+"-"+ip_end;
console.log(output);
}

This should do:
/* Remove the slash */
let rawIp = "10.31.68.1/22";
let rawIpParts = rawIp.split("/");
/* Split the new ip */
let ip = rawIpParts[0];
let ipParts = ip.split(".")
/* Append 0 */
ipParts[3] = ipParts[3].concat("0");
/* Output Array */
let output = []
/* Loop and increment */
for(let index = 0; index <= 4; index++) {
ipParts[2] = 1 + +ipParts[2];
output.push(ipParts.join("."));
}
/* Print */
console.log(output);
Hope this helps!

Related

Certain number question being missed in regex

I have the following if statement that removes the first instances of a number followed by the period. However, I am noticing it is missing to catch some of them (ex. "16.", "23.", "24.", etc.) and not sure why.
Here is the function:
function quesCleanUp(ques){
//Checks the first instance of "." and removes it and the number
if(ques.match(/[0-9]\./g)?.length > 1){//(ques.match(/./g)?.length > 1){
var quesClean = ques.replace(/^[^\.]*\./, '').trim();
} else{
var quesClean = ques.trim();
}
return quesClean;
}
The following for loop extracts the question from the google form:
for (var i = 0; i < items.length; i++) {
var item = items[i];
switch(item.getType()) {
case FormApp.ItemType.MULTIPLE_CHOICE:
var question = item.asMultipleChoiceItem();
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var question_type = "Multiple Choice";
var optns = [];
var answr;
var answers = question.getChoices();
answer_val = false;
for (var j = 0; j < answers.length; j++) {
var clean = answers[j].getValue().trim();
optns.push(clean);
if(answers[j].isCorrectAnswer()){
answr = answers[j].getValue().trim();
for(var x = 0; x < optns.length; x++){
if(answr == optns[x]){
answer_val = true;
break;
}
}
}
}
var multiJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON1: " + JSON.stringify(multiJSON));
constructedJSON[i+1] = multiJSON;
break;
case FormApp.ItemType.CHECKBOX:
var question = item.asCheckboxItem();
//var ques = question.getTitle().trim();//.replace(/\s/g, "");
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var question_type = "CheckBox";
var optns = [];
var answr = [];
var answers = question.getChoices();
for (var j = 0; j < answers.length; j++) {
var clean = answers[j].getValue().trim();//replace(/\s/g, "");
optns.push(clean);
if(answers[j].isCorrectAnswer()){
answr.push(answers[j].getValue().trim());
}
}
var checkJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON2: " + JSON.stringify(checkJSON));
constructedJSON[i+1] = checkJSON;
break;
case FormApp.ItemType.PARAGRAPH_TEXT:
var question = item.asParagraphTextItem();
//var ques = question.getTitle().trim();//.replace(/\s/g, "");
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var question_type = "free response";
var optns = [];
var answr;
var paraJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON3: " + JSON.stringify(paraJSON));
constructedJSON[i+1] = paraJSON;
break;
case FormApp.ItemType.TEXT:
var question = item.asTextItem();
//var ques = question.getTitle().trim();
var question_type = "free response";
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var optns = "";
var answr = "";
var textJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON4: " + JSON.stringify(textJSON));
constructedJSON[i+1] = textJSON;
break;
}
The following example is the type of question 16. What is the meaning of life?
And the expected output: What is the meaning of life?
Try using /[0-9]+./g to catch more than one digit
As a quick fix, in the function quesCleanUp() try to change the line:
if(ques.match(/[0-9]\./g)?.length > 1){//(ques.match(/./g)?.length > 1){
With:
if (ques.match(/^[0-9]+\./g).length > 0) {
I suspect you got the downvotes because you posted the code with glared typos. It looks like you didn't even try to debug it first. And as the icing on the cake you accepted a wrong answer.
And probably the function can be boiled down to just one line:
const quesCleanUp = q => q.replace(/^\d+\./,'').trim();
Here is how it works:
var questions = ['1. aaa', '16. What', '23. That', 'No nums'];
const quesCleanUp = q => q.replace(/^\d+\./,'').trim();
questions.forEach(q => console.log(quesCleanUp(q)));
Expected output:
aaa
What
That
No nums

how to use dynamic variable in update.js shopify

I want yo use test variable in update.js but it shows error when I use as variable but when I pass this value directly it works
can someone please tell me how can use dynamic variable to change quantity of existing products in cart
I have updated my code It will allow user to add only 5 items more than 5 items will be removed It will create string which will look like this
32082238341235:0,39470423048307:0,32164693278835:0,32164693835891:1
and finally the all IDs and qunatity will be updated by update.js
I have got error in last step its shows
{"status":404,"message":"Cart Error","description":"Cannot find variant"}
when i try to update all products
jQuery.getJSON('/cart.js', function(cart) {
var items_new = cart.items;
var count = 0;
count = cart.item_count;
var item_to_remove = count - 5;
if (count > 5) {
var item_to_remove = count - 5;
var combine = ""
if (item_to_remove > 0) {
for (var i = 0; i < items_new.length; i++) {
if (count > 5) {
var c_id = items_new[i].variant_id;
var c_quantity = items_new[i].quantity;
if (c_quantity >= item_to_remove) {
var q = c_quantity - item_to_remove
var data_multiple = c_id + ":" + q + ",";
debugger;
count = count - item_to_remove;
console.log(data_multiple);
var combine = combine + data_multiple;
} else {
var data_single = c_id + ":" + 0 + ",";
count = count - c_quantity;
item_to_remove = item_to_remove - c_quantity
console.log(data_single)
var combine = combine + data_single;
}
}
}
console.log(combine.slice(0, -1));
var test = combine.slice(0, -1);
console.log({
updates: {
test
}
});
jQuery.post('/cart/update.js', {
updates: {
test
}
});
}
t._rerenderCart()
}
t.sidebarDrawer.open()
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You need to store test as an object within parentheses {} and then pass to updates by using the spread ... operator.
var test = {39470423048307 : 0, 32164693278835 : 0, 32164693835891 : 1};
console.log({updates: {...test}});
jQuery.post('/cart/update.js', {updates:{...test}});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
In your updated code, you are passing a string to updates rather than an object. You should create an object from the data inside the for loop and pass that object to updates. See lines with // CHANGE HERE:
...
var combine = {};
if (item_to_remove > 0) {
for (var i = 0; i < items_new.length; i++) {
if (count > 5) {
var c_id = items_new[i].variant_id;
var c_quantity = items_new[i].quantity;
if (c_quantity >= item_to_remove) {
var q = c_quantity - item_to_remove;
// CHANGE HERE
combine[c_id] = q;
count = count - item_to_remove;
} else {
// CHANGE HERE
combine[c_id] = 0;
count = count - c_quantity;
item_to_remove = item_to_remove - c_quantity;
}
console.log(combine);
}
}
// CHANGE HERE
var test = combine;
console.log({
updates: test
});
jQuery.post('/cart/update.js', {
updates: test
});
...

Sort function not working as expected after putting getElementById this way

I'm a beginner figuring out my own first project but I can't get info about this case.
The application is supposed to receive data about a product, it's name, price, stock, number of sales and then sort them from the most sold to the less sold.
Here's the thing, I was trying to shorten how verbose the code was by putting this chunk this other way
so I went from this
var balanceVenta = (ev) => {
ev.preventDefault();
diseños.sort((a, b) => {
return (a.amountSold < b.amountSold) ? 1 : -1
});
document.getElementById("name1").innerHTML = diseños[0].designName;
document.getElementById("stock1").innerHTML = diseños[0].currentStock;
document.getElementById("price1").innerHTML = "$" + diseños[0].priceEa;
document.getElementById("sold1").innerHTML = diseños[0].amountSold;
document.getElementById("lastProduction1").innerHTML = diseños[0].productionAmount;
document.getElementById("name2").innerHTML = diseños[1].designName;
document.getElementById("stock2").innerHTML = diseños[1].currentStock;
document.getElementById("price2").innerHTML = "$" + diseños[1].priceEa;
document.getElementById("sold2").innerHTML = diseños[1].amountSold;
document.getElementById("lastProduction2").innerHTML = diseños[1].productionAmount;
document.getElementById("name3").innerHTML = diseños[2].designName;
document.getElementById("stock3").innerHTML = diseños[2].currentStock;
document.getElementById("price3").innerHTML = "$" + diseños[2].priceEa;
document.getElementById("sold3").innerHTML = diseños[2].amountSold;
document.getElementById("lastProduction3").innerHTML = diseños[2].productionAmount;
}
to this
var index = 0;
var balanceVenta = (ev) => {
ev.preventDefault();
diseños.sort((a, b) => {
return (a.amountSold > b.amountSold) ? 1 : -1
});
index++;
var prefixName = "name";
var prefixStock = "stock";
var prefixPrice = "price";
var prefixSold = "sold";
var prefixLastProd = "lastProduction";
document.getElementById(prefixName + index).innerHTML = diseños[index - 1].designName;
document.getElementById(prefixStock + index).innerHTML = diseños[index - 1].currentStock;
document.getElementById(prefixPrice + index).innerHTML = diseños[index - 1].priceEa;
document.getElementById(prefixSold + index).innerHTML = diseños[index - 1].amountSold;
document.getElementById(prefixLastProd + index).innerHTML = diseños[index - 1].productionAmount;
}
Everything works fine except for the sort function, which was working fine in the first hardcoded version but not working at all in the second one.
Pd: "diseños" is an Array which holds an object ("diseño" with no s) inside each index through this function
let diseños = [];
const addDesign = (ev) => {
ev.preventDefault();
let diseño = {
designName: document.getElementById("textBox1").value,
currentStock: document.getElementById("textBox2").value,
productionAmount: document.getElementById("textBox3").value,
priceEa: document.getElementById("textBox4").value,
amountSold: document.getElementById("textBox5").value
}
diseños.push(diseño);
document.forms[0].reset();
Can you guys help me out figure this one out?
You were close; you just need to put the code in a loop over diseños. I also simplified the sort logic a little, assuming amountSold is a number. Swap the position of a.amountSold and b.amountSold to change ascending to descending.
var balanceVenta = (ev) => {
ev.preventDefault();
diseños.sort((a, b) => a.amountSold - b.amountSold);
var prefixName = "name";
var prefixStock = "stock";
var prefixPrice = "price";
var prefixSold = "sold";
var prefixLastProd = "lastProduction";
for (var index = 0; index < diseños.length; index++) {
var suffix = index + 1;
document.getElementById(prefixName + suffix).innerHTML = diseños[index].designName;
document.getElementById(prefixStock + suffix).innerHTML = diseños[index].currentStock;
document.getElementById(prefixPrice + suffix).innerHTML = diseños[index].priceEa;
document.getElementById(prefixSold + suffix).innerHTML = diseños[index].amountSold;
document.getElementById(prefixLastProd + suffix).innerHTML = diseños[index].productionAmount;
}
}
make an object with all the properties you need, and then run this method over an array of your object every time you want to put it in order
var balanceVenta = diseños.OrderByDescending(x =>x.amountSold).ToList()

Javascript- Dynamic variable loop

I'm trying to reduce the amount of code I repeat.
Currently I have the below:
var item1H = $(".item-1").height();
var item1W = $(".item-1").height();
$(".item-1 .text").css('margin-left', -item1W/2);
$(".item-1 .text").css('margin-bottom', -item1H/2);
var item2H = $(".item-2").height();
var item2W = $(".item-2").height();
$(".item-2 .text").css('margin-left', -item2W/2);
$(".item-2 .text").css('margin-bottom', -item2H/2);
I'm looking to put this into a for loop where the variable number would count up to whatever number I needed it to stop.
You can make function like this and use whenever you want
toSetMargin(".item-2")
toSetMargin(".item-2")
function toSetMargin(objStr){
var widthTmp = $(objStr + ' .text').height();
var heightTmp = $(objStr + ' .text').height();
obj.css('margin-left', -widthTmp/2);
obj.css('margin-bottom', -heightTmp/2)
}
This code not impact any other code.
You could use $('[class^="item-"]') to get all the elements that have a class that starts with item-, and the loop over them
$('[class^="item-"]').each(function(){
var $elem = $(this);
var item1H = $elem.height();
var item1W = $elem.width();
$elem.find('.text').css({'margin-left': -item1W/2,'margin-bottom':-item1H/2});
});
Ooh boy, one of these problems. This should help (untested):
for(i=1;i<=STOPPING_NUMBER;i++){
window["item"+i+"H"] = $(".item-"+i).height();
window["item"+i+"W"] = $(".item-"+i).width(); //Was height, accident?
$(".item-"+i+" .text").css('margin-left', 0-window["item"+i+"W"]/2); //Hope this works lol
$(".item-"+i+" .text").css('margin-bottom', 0-window["item"+i+"H"]/2);
}
Guessing these lines:
var item1W = $(".item-1").height();
var item2W = $(".item-2").height();
Should have been:
var item1W = $(".item-1").width();
var item2W = $(".item-2").width();
You could do something like:
function setCSS(item,attr,val) {
$(item +" .text").css(attr, (val * -1)/2);
}
var i, max = 10;
for(i=1;i<=max;i++) {
setCSS(".item-"+ i,"margin-left",$(".item-"+ i).width());
setCSS(".item-"+ i,"margin-bottom",$(".item-"+ i).height());
}
Or something less flexible within the function:
function setCSS(item,w,h) {
$(item +" .text").css("margin-left", (w * -1)/2);
$(item +" .text").css("margin-bottom", (h * -1)/2);
}
var i, max = 10;
for(i=1;i<=max;i++) {
setCSS(".item-"+ i,$(".item-"+ i).width()),$(".item-"+ i).height());
}
Something like this should be pretty acceptible in your case, I guess:
for (var i = 1, len = someN; i < len; i++) {
var $item = $('.item-' + i);
$item.find('.text').css({
'margin-left': -$item.width() / 2,
'margin-bottom': -$item.height() / 2
});
}

Iterate over gmail threads and add a label with addlabel

I wish to run this standalone code twice a day, but cannot solve the exception on the addLabel, which is "impossible to find the method", any suggestion? I tried to change the for cycle as well as to assign a var to the threads[i] but nothing changed.
function salvaNote(){
var d = new Date();
d.setMonth(d.getMonth()-6);
var n = d.getFullYear() + "/" + addZero(d.getMonth()+1) + "/" + addZero(d.getDate());
var folderName = 'tavoloTecnico';
labelName = GmailApp.createLabel('tavoloTecnico');
var query = 'in:anywhere from:mariano.casillo#mit.gov.it OR from:donato.castigliego#mit.gov.it has:attachment subject:previsioni filename:xls '+ 'after:'+n;
var threads = GmailApp.search(query);
var quanteMail = threads.length;
for ( var i = 0 ; i < quanteMail; i++) {
threads[i].addLabel(labelName);
var mesgs = threads[i].getMessages();
for(var j in mesgs){
var attachments = mesgs[j].getAttachments();
for(var k in attachments){
var attachment = attachments[k];
var attachmentBlob = attachment.copyBlob();
var file = DriveApp.createFile(attachmentBlob);
DriveApp.getFoldersByName(folderName).next().addFile(file);
}
}
}
}

Categories

Resources