javascript - How can we increment and then decrement a counter without conditionals? -
i'm looking clever way increment , decrement counter variable. want counter variable begin @ low value , increment, towards higher value. 1 time reaches higher value, counter decrements until reaches lower value. 1 time reaches lower value, counter increments 1 time again higher value ... think point.
i working on a canvas animation i'd employ cleverness, without using if
or other conditional tests:
here conditional logic handles counter variable:
incrementing = true foo = -> length += 1 if incrementing length -= 1 if not incrementing incrementing = false if length > 100 incrementing = true if length < 1
initially, thought utilize modulo. however, modulo partition resets counter lower value -- doesn't decrement counter 1 time reaches top value.
0 % 10 = 0 1 % 10 = 1 2 % 10 = 2 3 % 10 = 3 4 % 10 = 4 5 % 10 = 5 6 % 10 = 6 7 % 10 = 7 8 % 10 = 8 9 % 10 = 9 10 % 10 = 0 11 % 10 = 1 12 % 10 = 2 13 % 10 = 3
i'm sure there has way without using conditional tests. assuming bottom value of 0 , top value of 10, method should output following.
? = 0 ? = 1 ? = 2 ? = 3 ? = 4 ? = 5 ? = 6 ? = 7 ? = 8 ? = 9 ? = 8 ? = 7 ? = 6 ? = 5
first let's @ waves !
hello waves !
can identify 1 matches needs ?
if guessed triangle wave, you're right !
triangle wave oscillates uniform slope until hits min or max, , slope inverted.
two things work out here:
the origin of function start in middle of wave the wave oscillatesx
-x
we want start output @ 0
, include positive values
function triangle(t, a) { homecoming math.abs(((t + a/2) % a) - a/2); }
let's seek out
for (var i=0; i<20; i++) { console.log(i, triangle(i, 10)); }
output
0 0 1 1 2 2 3 3 4 4 5 5 6 4 7 3 8 2 9 1 10 0 11 1 12 2 13 3 14 4 15 5 16 4 17 3 18 2 19 1
so when phone call triangle(i, 10)
10
"period". tells how many steps want have in our function before repeats.
a period of 6
give 6 values, 0, 1, 2, 3, 2, 1
a period of 4
give 4 values, 0, 1, 2, 1
etc
if want go 0-9
, need period of 20
javascript coffeescript logic
No comments:
Post a Comment