18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Deployment Issues<br />

iTestValue = 0;<br />

} while (--iLoopCount > 0);<br />

The variable iIterations contains the number of times that the loop that should be executed. The<br />

variable iLoopCount contains the number of times it is necessary to repeat the do..while loop. The<br />

iTestValue variable represents which case in the switch statement should be executed the very first<br />

time the loop is entered; every other time, execution starts with case 0 and runs through all the rest<br />

(notice that no break statements stop execution after a case statement is executed). If you apply Duff’s<br />

Device to the previous example, this is the result:<br />

var aValues = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];<br />

var iIterations = aValues.length;<br />

var iLoopCount = Math.ceil(iIterations / 8);<br />

var iTestValue = iIterations % 8;<br />

var iSum = 0;<br />

var i = 0;<br />

do {<br />

switch (iTestValue) {<br />

case 0: iSum+= aValues[i++];<br />

case 7: iSum+= aValues[i++];<br />

case 6: iSum+= aValues[i++];<br />

case 5: iSum+= aValues[i++];<br />

case 4: iSum+= aValues[i++];<br />

case 3: iSum+= aValues[i++];<br />

case 2: iSum+= aValues[i++];<br />

case 1: iSum+= aValues[i++];<br />

}<br />

iTestValue = 0;<br />

} while (--iLoopCount > 0);<br />

Notice that iIterations has been set to the number of values in the array, and the iSum and i variables<br />

have been added. The iSum variable, of course, holds the result of adding all the numbers in the array; the<br />

i variable is used as an iterator to move through the array (just as with the for and do..while loops).<br />

Before the loop is executed, iLoopCount is equal to 3, meaning that the loop is executed three times. The<br />

value of iTestValue is equal to 4, so when execution enters the first loop, it skips down to case 4 in the<br />

switch statement. After those four lines are executed, iTestValue is set back to 0. From that point on,<br />

whenever the loop executes, all cases beginning at case 0 are executed.<br />

Greenburg further optimized his <strong>JavaScript</strong> version of Duff’s Device by splitting the single do..while<br />

loop into two separate loops. The algorithm is as follows:<br />

var iLoopCount = iIterations % 8;<br />

while (iLoopCount--) {<br />

[execute statement]<br />

}<br />

587

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!