Skip to content

Instantly share code, notes, and snippets.

@gugiserman
Last active August 29, 2015 14:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gugiserman/94bb936210c7b2abfe58 to your computer and use it in GitHub Desktop.
Save gugiserman/94bb936210c7b2abfe58 to your computer and use it in GitHub Desktop.
Partition of array in rows of given columns (AngularJS Filter)
.filter 'partition', ($cacheFactory) ->
cache = $cacheFactory 'partition'
(list, colLimit) ->
return if !list or list.length < 1
# PARTITION OF ORIGINAL ARRAY
groups = []
index = 0
for i in [0..Math.ceil(list.length / colLimit) - 1]
groups.push list[index..index + (colLimit - 1)]
index += colLimit
# CACHE IID
cacheId = JSON.stringify(list) + colLimit
# CHECKS FOR PREVIOUS CACHED VERSION
cached = cache.get(cacheId)
return cached if JSON.stringify(groups) is JSON.stringify(cached)
# ELSE, CACHE NEW ARRAY AND RETURNS IT
cache.put(cacheId, groups)
return groups
.filter('partition', function($cacheFactory) {
var cache;
cache = $cacheFactory('partition');
return function(list, colLimit) {
var cacheId, cached, groups, i, index, _i, _ref;
if (!list || list.length < 1) {
return;
}
groups = [];
index = 0;
for (i = _i = 0, _ref = Math.ceil(list.length / colLimit) - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; i = 0 <= _ref ? ++_i : --_i) {
groups.push(list.slice(index, +(index + (colLimit - 1)) + 1 || 9e9));
index += colLimit;
}
cacheId = JSON.stringify(list) + colLimit;
cached = cache.get(cacheId);
if (JSON.stringify(groups) === JSON.stringify(cached)) {
return cached;
}
cache.put(cacheId, groups);
return groups;
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment