Skip to content

Instantly share code, notes, and snippets.

@intellix
Created December 5, 2016 21:25
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 intellix/6b8a1f064b917f8583b8ee57715a56af to your computer and use it in GitHub Desktop.
Save intellix/6b8a1f064b917f8583b8ee57715a56af to your computer and use it in GitHub Desktop.
(function() {
'use strict';
angular
.module('chunkFilter')
.filter('chunk', chunk);
function chunk() {
return function(value, size, vertical, preserveKeys) {
var chunks = [];
var chunkCount = size;
var chunkIndex;
if (!value || value.length === 0) {
return value;
}
vertical = vertical || false;
preserveKeys = preserveKeys || false;
if (!vertical) {
chunkCount = Math.ceil(value.length / size);
}
for (chunkIndex = 0; chunkIndex < chunkCount; chunkIndex++) {
chunks.push([]);
}
chunkIndex = 0;
value.forEach(function(value, key) {
if (preserveKeys) {
chunks[chunkIndex][key] = value;
} else {
chunks[chunkIndex].push(value);
}
if (++chunkIndex === chunkCount) {
chunkIndex = 0;
}
});
// Hack against infdig when used in view - http://stackoverflow.com/a/29117743
if (!value.$$splitListFilter || !angular.equals(value.$$splitListFilter, chunks)) {
value.$$splitListFilter = chunks;
}
return value.$$splitListFilter;
};
}
})();
describe('module: chunkFilter', function() {
beforeEach(module('chunkFilter'));
var $filter;
beforeEach(inject(function(_$filter_) {
$filter = _$filter_;
}));
describe('filter: xcChunkFilter', function() {
it('should chunk horizontally', function() {
var value = [1, 2, 3, 4, 5, 6];
var size = 2;
var vertical = false;
var preserveKeys = false;
var chunks = $filter('chunk')(value, size, vertical, preserveKeys);
expect(chunks).toEqual([
[1, 4], [2, 5], [3, 6]
]);
});
it('should chunk vertically', function() {
var value = [1, 2, 3, 4, 5, 6];
var size = 2;
var vertical = true;
var preserveKeys = false;
var chunks = $filter('chunk')(value, size, vertical, preserveKeys);
expect(chunks).toEqual([
[1, 3, 5], [2, 4, 6]
]);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment