Created
December 4, 2015 10:38
-
-
Save sorenlouv/5b1d85e997dd4f635af3 to your computer and use it in GitHub Desktop.
Optimized range function for angular
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I stumbled upon here from your SO answer, just a curious query, may I know why the range of 70 specifically ?
Thanks!