Welcome Guest [Log In] [Register]

About Me

I code. What else is there to say? ;)
Categories
Codes (2)
General (0)
Tutorials (3)

Readers Online

0 Members, 1 Guest

Jun 04

Quick Tip #2: 1's and 0's

Hey guys! Long time no see. I'm here to give you a quick technique that I've started to use more and more with simple codes that have some sort of rotation.

Suppose you have an array of two values. You need to keep switching between those values. One good example is my inbox flasher script:
Code:
 

<script type="text/javascript">
//////////////////////////
// Inbox Flasher 1.0 //
//By Choco of ZB Support//
// June 4th, 2008 //
//////////////////////////
interval = 300; //Flash rate in milliseconds
color = [];
color[0] = "white"; //Color one
color[1] = "red"; //Color two -- script flashes between these two

//Don't edit
l=0;
function flash() {
z=$("#menu_pm a")[0];
$(z).css("color",color[l]);
l=(0-l)+1;
}
$(function(){$("#menu_pm a").each(function() {x=$(this).html();if(x.match(/small\>(\d+)</gi)) {y=RegExp.$1;if(y>0){q=setInterval("flash()",interval);$(this).attr("id","flash");}}});});
</script>


As you can see, I have to keep changing the color of the link every 300 milliseconds. Now, my original flash() function, the one that actually changes the color, looked like this:

Code:
 

function flash() {
z=$("#menu_pm a")[0];
if(l==0) {
l=1;
$(z).css("color",color[0]);
} else {
l=0;
$(z).css("color",color[1]);
}
}

Look -- I managed to cut the function down by 50% - from 10 to 5 - using simple math. Here's how it works.

Take a peek at the original flash function, the second one I posted. It's quite simple:
1. Fetch the link
2. Check which color we're supposed to flash (l is either 0 or 1)
3. If 0, change l to 1 and change the color to color[0]
4. If 1, do the opposite of #3
5. End function

However, what we can do is what I did in the new flash function:
1. Fetch the link
2. Set the color to color[l] (which is either color[0] or color[1])
3. Change l from 1 to 0 or 0 to 1
4. End function

The bold is where the easiest of mathematical functions, subtraction and addition, can cut code down substantially.
While taking a math final a couple of years ago, I found a problem that I thought of was hard to solve -- how do we convert 0 to 1 and 1 to 0 if you only have one equation?

After spending most of the final working on that alone, I realized the correct way.
If n is either 0 or 1, then:
f(n) = -n+1
So:
f(0) = -0+1 = 1
f(1) = -1+1 = 0

You may scoff that I actually bothered to write a blog entry on that, but you have no idea how much I use this formula. It's extremely handy!

Hope that helps someone.
-Choco
Posted in Tutorials at 4:52 pm · No comments
  1. Add new comment: