My code that I'd like to condense:
document.getElementById("costA").innerHTML = currentCost[0];
document.getElementById("costB").innerHTML = currentCost[1];
document.getElementById("costC").innerHTML = currentCost[2];
document.getElementById("costD").innerHTML = currentCost[3];
document.getElementById("costE").innerHTML = currentCost[4];
document.getElementById("costF").innerHTML = currentCost[5];
document.getElementById("costG").innerHTML = currentCost[6];
document.getElementById("costH").innerHTML = currentCost[7];
document.getElementById("amountA").innerHTML = building[0];
document.getElementById("amountB").innerHTML = building[1];
document.getElementById("amountC").innerHTML = building[2];
document.getElementById("amountD").innerHTML = building[3];
document.getElementById("amountE").innerHTML = building[4];
document.getElementById("amountF").innerHTML = building[5];
document.getElementById("amountG").innerHTML = building[6];
document.getElementById("amountH").innerHTML = building[7];
document.getElementById("bonusA").innerHTML = currentBonuses[0];
document.getElementById("bonusB").innerHTML = currentBonuses[1];
document.getElementById("bonusC").innerHTML = currentBonuses[2];
document.getElementById("bonusD").innerHTML = currentBonuses[3];
document.getElementById("bonusE").innerHTML = currentBonuses[4];
document.getElementById("bonusF").innerHTML = currentBonuses[5];
document.getElementById("bonusG").innerHTML = currentBonuses[6];
document.getElementById("bonusH").innerHTML = currentBonuses[7];
I see three main sections that look like they can be condensed. I'd also, perhaps, prefer a way to be able to add or subtract an arbitrary number of buildings without changing too much of the code.
You can update in a loop. Following is a very basic representation:
var alphabetArr = ["A", "B","C","D","E","F","G","H"];
alphabetArr.forEach(function(row, i){
document.getElementById("cost" + row).innerHTML = currentCost[i];
document.getElementById("amount" + row).innerHTML = building[i];
document.getElementById("bonus" + row).innerHTML = currentBonuses[i];
})
Just in case, here is another way to do it without hard coding an array of letters. Another benefit is that this avoids Array.prototype.forEach which is not available in Internet Explorer 8
var start = "A".charCodeAt(0);
var end = "H".charCodeAt(0);
for (var i = start; i <= end; i += 1) {
var row = String.fromCharCode(i);
document.getElementById('cost' + row).innerHTML = currentCost[i - start];
document.getElementById('amount' + row).innerHTML = building[i - start];
document.getElementById('bonus' + row).innerHTML = currentBonuses[i - start];
}
Related
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()
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
});
}
View itself is sorted by decending order!(First column is "New_Exam_No")
currentExamNo = doc.getItemValueString("New_Exam_No");
var Candvw:NotesView = database.getView("(Exam Application Subject Sort by ExamNo)");
var CandEntry:NotesViewEntry=Candvw.getEntryByKey(doc.getItemValueString("New_Exam_No"),true);
if (CandEntry!=null) //If have exam no, use this condition
{
var CandDoc = CandEntry.getDocument()
if (Canddoc.hasItem("Candidate_No")==true) // assign Candidate No yet?Yes!
{
var CandNo = Canddoc.getItemValueString("Candidate_No");
LCandNo = "LSBS"
MidCandNo = #Left(CandNo,7)
MCandNo = #TextToNumber(#Right(MidCandNo,2)) + 1;
CNo = #Right("00"+#Text(MCandNo),2);
RExamNo = currentExamNo;
CandidateNo = LCandNo + "/" + CNo + "/" +RExamNo ;
}
else
{
CandidateNo = "LSBS/01/" + currentExamNo;
}
}
else
{
CandidateNo = "LSBS/01/" + currentExamNo;
}
Why i always get the LSBS/01/examno as it doesn't add on 1.
getEntryByKey() takes a Vector rather than a String. Try:
var key:java.util.Vector = new java.util.Vector();
key.add(doc.getItemValueString("New_Exam_No"));
var CandEntry:NotesViewEntry=Candvw.getEntryByKey(key,true);
It's been a while since I used SSJS, but I think that should work.
function changeText(getString){
var smiles_from_to = new Array();
smiles_from_to[":)"] = "ab"; smiles_from_to[":-)"] = "ab";
smiles_from_to[":("] = "ac"; smiles_from_to[":-("] = "ac";
smiles_from_to["B)"] = "af"; smiles_from_to["B-)"] = "af";
smiles_from_to[";("] = "crygirl2"; smiles_from_to[";-("] = "crygirl2";
smiles_from_to[":-*"] = "aw"; smiles_from_to[":*"] = "aw";
smiles_from_to[":D"] = "ag"; smiles_from_to[":-D"] = "ag";
smiles_from_to["(devil)"] = "aq"; smiles_from_to["(wtf)"] = "ai";
smiles_from_to["(sos)"] = "bc"; smiles_from_to["(boom)"] = "bb";
smiles_from_to["(rofl)"] = "bj"; smiles_from_to["xD"] = "bj";
smiles_from_to["(music)"] = "ar"; smiles_from_to["(angel)"] = "aa";
smiles_from_to["(beer)"] = "az"; smiles_from_to["(omg)"] = "bu";
smiles_from_to["(dance)"] = "bo"; smiles_from_to["(idiot)"] = "bm";
smiles_from_to["(clap)"] = "bi"; smiles_from_to["(gotkiss)"] = "as";
var replaced = getString;
for(var key in smiles_from_to){
replaced = replaced.replace(key, "<img src='"+chrome.extension.getURL("images/"+smiles_from_to[key]+".gif")+"' />");
}
return replaced;
}
Hi everyone ,I need to optimize code for something more simple, so try to avoid for loop..
"var replaced" is a huge html code (content of div that contains 100 lines of messages with date, username, userinfo(tooltip), message,.....)
This code is a piece from my chrome extension. so i cant do it php side.
You can use a single giant regex, of the form /:\)|:\(|.../g, then pass a callbacka as the replacement that looks up the match in your lookup object.
The purpose of the code is to build a series of nested HTML using information in objects:
Here are the informational objects I created:
function branch(level,sciname,comname,parent,children){
this.level = level;
this.sciname = sciname;
this.comname = comname;
this.parent = parent;
this.children = children;}
var animalia = new branch(1,'Animalia','Animals',"",['chordata']);
var chordata = new branch(2,'Chordata','Chordates',animalia,['petromyzontida','actinopterygii']);
var actinopterygii = new branch(3,'Actinopterygii','Ray-finned Fishes',chordata,['siluriformes','scorpaeniformes','salmoniformes','percopsiformes','perciformes','osteoglossiformes','osmeriformes','lepisosteiformes','gasterosteiformes','gadiformes','esociformes','cyprinodontiformes','cypriniformes','clupeiformes','atheriniformes','anguilliformes','amiiformes','acipenseriformes']);
var petromyzontida = new branch(3,'Petromyzontida','Lampreys',chordata,['petromyzontiformes']);
And here is the script:
function CreateDiv(parent,child,z,width,height,top,left,bgcolor){
var parent_ = document.getElementById(parent);
var newdiv = document.createElement("div");
newdiv.setAttribute("id",child);
newdiv.style.zIndex = z;
newdiv.style.position = "absolute";
newdiv.style.width = width + "%";
newdiv.style.height = height + "%";
newdiv.style.top = top + "%";
newdiv.style.left = left + "%";
newdiv.style.backgroundColor = bgcolor;
parent_.appendChild(newdiv);}
function CreateTree(){
var firstdiv = document.createElement("div");
firstdiv.setAttribute("id","animalia");
document.getElementById("container1").appendChild(firstdiv);
var parent1 = "animalia";
var children1 = window[parent1].children;
var numbchildren1 = children1.length;
var rowcounter1 = 1;
var columncounter1 = 0;
for (i=0;i<numbchildren1;i++){
var child1 = children1[i];
var z1 = 2;
var columns1 = Math.ceil(Math.sqrt(numbchildren1));
var width1 = (100/columns1) - 2;
var rows1 = Math.ceil(numbchildren1/columns1);
var height1 = (100/rows1) - 2;
var top1 = rowcounter1*height1 - height1 + 1;
var left1 = columncounter1*width1 + 1;
var bgcolor1 = "#B43333";
CreateDiv(parent1,child1,z1,width1,height1,top1,left1,bgcolor1);
var numbchildren2 = window[child1].length;
if ((i/rowcounter1) == columns1){
rowcounter1 = rowcounter1 + 1;}
else {rowcounter1 = rowcounter1;}
if (columncounter1 == columns1){
columncounter1 = 1;}
else {columncounter1 = columncounter1 + 1;}
var rowcounter2 = 1;
var columncounter2 = 0;
console.log("before:" + columncounter2);
for (j=0;j<numbchildren2;j++){
console.log("after:" + columncounter2);
var child2 = children2[j];
var z2 = 3;
var columns2 = Math.ceil(Math.sqrt(numbchildren2));
var width2 = (100/columns2) - 1;
var rows2 = Math.ceil(numbchildren2/columns2);
var height2 = (100/rows2) - 1;
var top2 = rowcounter2*height2 - height2 + 1;
var left2 = columncounter2*width2 - width2 + 1;
var bgcolor2 = "#B48233";
CreateDiv(parent2,child2,z2,width2,height2,top2,left2,bgcolor2);}}}
I've run the code through a debugger dozens of times and I get no errors. Yet the script does not fully execute. I suspected an infinite loop but I fail to see why that would occur and after going over the code in great detail, I can find no real problems. I can tell where the code seems to break. There are two console.log() statements in the above code. The first console statement gets properly logged, but the second one does not. The debugger shows no errors (Firebug), but the code still fails to fully execute. Please help! And suggestions or criticism will be very welcome as I'm still learning some of the basics.
As a note: Eventually, I will add to this process to create several layers of nested elements, but wanted to get just the first couple layers right before I begin nesting things further as once I do that additional nesting should be relatively easy.
Compare
var children1 = window[parent1].children;
to
var numbchildren2 = window[child1].length;
I think the second one is missing a ".children" before the length. As Shaed, pointed out, numbchildren2 being incorrectly initialized was the most probable cause of the for loop not running, so you should have been investigating that.
I am not familiar with your syntax of window[elementID] to get an element, but I am pretty sure it does not work. Try using document.getElementById instead.
http://jsfiddle.net/M9jtt/