Created
January 7, 2015 22:41
-
-
Save yangchristian/d9275785f85a39c490fc to your computer and use it in GitHub Desktop.
Weighted modulus Angular filter
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
| 'use strict'; | |
| var _ = _ || require('lodash'); | |
| /** | |
| * For an input array, return a multidimensional array with elements distributed | |
| * across rows. Number of elements in each row is determined by a "weighted modulus", | |
| * e.g. keeping a running total based on each elements `dividendProp` and modulo the | |
| * specified `divisor`. | |
| * | |
| * Example using an `inputArray` of Twitter Bootstrap columns that should wrap | |
| * into a new row after 12 columns: | |
| * | |
| * var columns = [ | |
| * { cols: 8, otherData: 'Random other data' }, | |
| * { cols: 4 }, | |
| * { cols: 12 } | |
| * ] | |
| * | |
| * Usage: | |
| * <div class="row" ng-repeat="rows in columns|weightedModulus:12:'cols'"> | |
| * <div class="col-md-{{col['cols']}}" ng-repeat="col in rows"> | |
| * <!-- column content --> | |
| * </div> | |
| * </div> | |
| * | |
| * Note that output is undefined if `inputArray` elements doesn't line up with rows nicely. | |
| * | |
| * @param {Array} input array | |
| * @param {Integer} modulo divisor | |
| * @param {String} property in each element in the input array to use for running dividend | |
| * @return {Array} multidimensional array consisting of inputArray elements | |
| */ | |
| angular.module('app.filters').filter('weightedModulus', function() { | |
| // Need to memoize to return same result array, otherwise Angular $digest cycle | |
| // considers each result different, resulting in infinite digest loops | |
| return _.memoize(function(inputArray, divisor, dividendProp) { | |
| var rows = []; | |
| var currentRow; | |
| var runningDividend = 0; | |
| for (var i = 0; i < inputArray.length; i++) { | |
| if(runningDividend % divisor === 0) { | |
| currentRow = []; | |
| rows.push(currentRow); | |
| } | |
| var el = inputArray[i]; | |
| currentRow.push(el); | |
| runningDividend += el[dividendProp]; | |
| } | |
| return rows; | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment