Skip to content

Instantly share code, notes, and snippets.

@thomasd
Created December 8, 2009 02:09
Show Gist options
  • Save thomasd/251355 to your computer and use it in GitHub Desktop.
Save thomasd/251355 to your computer and use it in GitHub Desktop.
Circulates the given number between the min-, max-boundaries (boundaries included)
/*
Script: Number.circulate.js
Extension for Mootools Number Native
License:
MIT-style license.
Copyright:
Copyright (c) 2009-2010 [Thomas Dullnig](http://thomasdullnig.blogspot.com/).
Code:
[Thomas Dullnig](http://thomasdullnig.blogspot.com/).
Description:
Circulates the given number between the min-, max-boundaries (boundaries included)
Examples may help:
(11).circulate(5, 10) == 5
(12).circulate(5, 10) == 6
(13).circulate(5, 10) == 7
(14).circulate(5, 10) == 8
(15).circulate(5, 10) == 9
(16).circulate(5, 10) == 10
(17).circulate(5, 10) == 5
(18).circulate(5, 10) == 6
and so on...
Same goes for numbers smaller than the min-value:
(4).circulate(5, 10) == 10
(3).circulate(5, 10) == 9
(2).circulate(5, 10) == 8
and so on...
Even with negative values:
(-2).circulate(0, 2) == 1
or
(3).circulate(-4, -2) == -3
*/
Number.implement({
'circulate': function(min, max) {
if (!(this > max || this < min)) {return this;}
var gap = max - min + 1;
return (this > max ? min - 1 + (((this - max) % gap) || gap) : max + 1 - (((min - this) % gap) || gap));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment