patternjavascriptMinor
Reducing code with two identical objects
Viewed 0 times
objectswithidenticalreducingtwocode
Problem
I have two identical objects on the page, so I get more of the same lines of code. Can anything be made simpler, perhaps with merging?
for(var i=0;i<ticks.length,i<ticks2.length;i++) {
var tick = ticks[i];
var tick2 = ticks2[i];
var tickCenter = tick.offsetWidth / 2
var offset = (i - currentTick) * pixelsPerTick;
var percent = 1-(Math.abs(i-currentTick)/10);
tick2.style.top = ((offset + center - tickCenter)|0) + "px";
tick2.style.opacity = percent;
tick.style.top = ((offset + center - tickCenter)|0) + "px";
tick.style.opacity = percent;
}Solution
You can combine the two identical assignments at the end into the same line rather than recalculating the same value again:
I also fixed your condition in the
You could also avoid some of the intermediate values, but I personally would preserve them the way you have them because of the readability/understandability advantage of having it this way vs. putting them all in one giant formula.
for (var i = 0; i < ticks.length && i < ticks2.length; i++) {
var tick = ticks[i];
var tick2 = ticks2[i];
var tickCenter = tick.offsetWidth / 2
var offset = (i - currentTick) * pixelsPerTick;
var percent = 1 - (Math.abs(i - currentTick) / 10);
tick.style.top = tick2.style.top = ((offset + center - tickCenter) | 0) + "px";
tick.style.opacity = tick2.style.opacity = percent;
}I also fixed your condition in the
for loop so that it safely checks both .length values.You could also avoid some of the intermediate values, but I personally would preserve them the way you have them because of the readability/understandability advantage of having it this way vs. putting them all in one giant formula.
Code Snippets
for (var i = 0; i < ticks.length && i < ticks2.length; i++) {
var tick = ticks[i];
var tick2 = ticks2[i];
var tickCenter = tick.offsetWidth / 2
var offset = (i - currentTick) * pixelsPerTick;
var percent = 1 - (Math.abs(i - currentTick) / 10);
tick.style.top = tick2.style.top = ((offset + center - tickCenter) | 0) + "px";
tick.style.opacity = tick2.style.opacity = percent;
}Context
StackExchange Code Review Q#56070, answer score: 6
Revisions (0)
No revisions yet.