Forum Moderators: open

Message Too Old, No Replies

Wrapping Numbers

         

Jacob or JaF

5:24 pm on Aug 7, 2007 (gmt 0)

10+ Year Member



How can I wrap a number in JavaScript?

Example:
var number=3;
number=number.wrap(0, 2);

gives 0

Is there abuilt in function or is there a script out there?

Thank you,
Jacob

daveVk

2:16 am on Aug 8, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Do you mean modulus/remainder?

example A = 14 % 12, gives A = 2

Jacob or JaF

2:16 pm on Aug 8, 2007 (gmt 0)

10+ Year Member



Didn't mean to double post.

[edited by: Jacob_or_JaF at 2:17 pm (utc) on Aug. 8, 2007]

Jacob or JaF

2:16 pm on Aug 8, 2007 (gmt 0)

10+ Year Member



Not really, I want a function that 'wraps' a number between two numbers.

Another exapmle:
var a=100;
a=a.wrap(45, 65);
alert(a); //gives 58.

TNT Basic [tntbasic.com] has this function, all I have to do is create a new file and add one line of code, print wrap(100, 45, 65), and it gives me 58.

Fotiman

2:50 pm on Aug 8, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month




Not really, I want a function that 'wraps' a number between two numbers.

I still have no idea what that means. I've never heard this terminology used... wrapping a number? Never heard of it.

Here's your example:


var a=100;
a=a.wrap(45, 65);
alert(a); //gives 58.

So you have a number (100) that you call this 'wrap' method on with 2 other numbers (45 and 65). This returns 58? What is 58? Is it a random number? Is there some mathmatical formula to what wrap is supposed to do?

Jacob or JaF

1:26 am on Aug 9, 2007 (gmt 0)

10+ Year Member



This seems to be very hard to explain...

Here's another example of how it works:
a=9;
a=a.wrap(-3, 0);

So, since 9>0, we start at -3, here's the list (the output number is allowed to be -3, -2, -1, and 0), so we add one and keep looping through that list until we moved 9 places.

I've found this function very useful while using TNT Basic.

daveVk

4:48 am on Aug 9, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Number.prototype.wrap = function( low, high ) {
var range = high - low;
var mod = this % range; // 0 -> range
return mod + low; // low -> high
}

Jacob or JaF

1:38 pm on Aug 9, 2007 (gmt 0)

10+ Year Member



Thank you very much, Dave!

That works great, although a little different from TB, but I think TB's ones a little off.

So, thanks again!
Jacob

daveVk

6:25 am on Aug 10, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Possible alternative, such that if input is within range (low to high ) it is returned unchanged, perhaps more like TB.

Number.prototype.wrap = function( low, high ) {
var range = high - low;
var mod = (this-low) % range; // 0 -> range
return mod + low; // low -> high
}