Skip to content

Instantly share code, notes, and snippets.

@sorenlouv
Created December 4, 2015 10:38
Show Gist options
  • Save sorenlouv/5b1d85e997dd4f635af3 to your computer and use it in GitHub Desktop.
Save sorenlouv/5b1d85e997dd4f635af3 to your computer and use it in GitHub Desktop.
Optimized range function for angular
// Extended answer: http://stackoverflow.com/questions/11873570/angularjs-for-loop-with-numbers-ranges/17124017#17124017
// By caching the function result, it can become orders of magnitudes more efficient (depending on how big the range is)
// jsPerf: http://jsperf.com/memoizer-range/9
$scope.range = (function() {
var cache = {};
return function(min, max, step) {
var isCacheUseful = (max - min) > 70;
var cacheKey;
if (isCacheUseful) {
cacheKey = max + ',' + min + ',' + step;
if (cache[cacheKey]) {
return cache[cacheKey];
}
}
var _range = [];
step = step || 1;
for (var i = min; i <= max; i += step) {
_range.push(i);
}
if (isCacheUseful) {
cache[cacheKey] = _range;
}
return _range;
};
})();
@jamesbondo
Copy link

it's tested right?
Also, you forgot the input to the function... you had it in stackoverflow

@sachingadagi
Copy link

I stumbled upon here from your SO answer, just a curious query, may I know why the range of 70 specifically ?
Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment