Skip to content

Instantly share code, notes, and snippets.

@plukevdh
Created February 4, 2014 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plukevdh/8808275 to your computer and use it in GitHub Desktop.
Save plukevdh/8808275 to your computer and use it in GitHub Desktop.
Crazy Range Explain
// same things as ~~
// basically rounds to an integer (when x is a float)
// see: http://stackoverflow.com/questions/4055633/what-does-do-in-javascript
function doubleTilde(x) {
if(x < 0) return Math.ceil(x);
else return Math.floor(x);
}
function range(to, from, step) {
// set defaults
var f = from || 1; // (f=from||1)
var s = step || 1; // (s=step||1)
// how far we're going to grab (range)
// division means we may have a fraction...
var r = (to - f) / s; // ((to-(f=from||1))/(s=step||1))
// round out the fraction
r = doubleTilde(r); // ~~((to-(f=from||1))/(s=step||1))
// offset for users as arrays are zero indexed
r += 1; // 1+~~((to-(f=from||1))/(s=step||1)))
// give me a bunch of empty (undefined) object to placehold in the array
var items = Array(r);
// create an empty array the size of the range we are getting with the placeholder items
var blankArray = Array.apply(0,items)
// walk over the blank array (map) and perform the following function at each step
// returns the mapped array
return blankArray.map( function(e,i) {
// i = the index of the item in the blank array
// s = our step count
// f = where we start from
//
// so this is basically iterating over an empty array and filling in values offsetting by the "from" param
// we gave it and stepping as far as we told it in the "step" param
return i*s+f;
});
}
function range_orig(to, from, step) {
return Array.apply(0,Array(1+~~((to-(f=from||1))/(s=step||1)))).map( function(e,i){return i*s+f});
}
range(50, 0, 5);
range(50);
range_orig(50, 0, 5);
range_orig(50);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment