Skip to content

Commit 2f26bda

Browse files
committed
Add mode filter
1 parent 9d8017a commit 2f26bda

File tree

4 files changed

+73
-0
lines changed

4 files changed

+73
-0
lines changed

README.md

+9
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@
7171
- [shortFmt](#shortfmt)
7272
- [byteFmt](#bytefmt)
7373
- [kbFmt](#kbfmt)
74+
- [mode] (#mode)
7475
- [Boolean](#boolean)
7576
- [isNull](#isnull)
7677
- [isDefined](#isdefined)
@@ -1222,6 +1223,14 @@ Converts kilobytes into formatted display<br/>
12221223
1 MB
12231224
1.00126 GB
12241225
1226+
```
1227+
+###mode
1228+
Calculates the mode value from all values within an array<br/>
1229+
**Usage:** ```array | mode```
1230+
```html
1231+
{{ [12,7,5,7] | mode }}
1232+
<!--result
1233+
7
12251234
```
12261235
#Boolean
12271236
>Used for boolean expression in chaining filters

src/_filter/math/mode.js

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* @ngdoc filter
3+
* @name mode
4+
* @kind function
5+
*
6+
* @description
7+
* Math.mode will get an array and return the mode value.
8+
*/
9+
angular.module('a8m.math.mode', ['a8m.math'])
10+
.filter('mode', ['$math', function ($math) {
11+
return function (input) {
12+
13+
if(!isArray(input)) {
14+
return input;
15+
}
16+
17+
var modeMap = {};
18+
var mode = input[0];
19+
var maxCount = 1;
20+
for (var i = 0; i < input.length; i++) {
21+
var val = input[i];
22+
if(isDefined(modeMap[val])){
23+
modeMap[val]++;
24+
} else {
25+
modeMap[val] = 1;
26+
}
27+
28+
if(modeMap[val] > maxCount){
29+
mode = val;
30+
maxCount = modeMap[val];
31+
}
32+
}
33+
34+
return mode;
35+
};
36+
}]);

src/filters.js

+1
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ angular.module('angular.filter', [
6666
'a8m.math.byteFmt',
6767
'a8m.math.kbFmt',
6868
'a8m.math.shortFmt',
69+
'a8m.math.mode',
6970

7071
'a8m.angular',
7172
'a8m.conditions',

test/spec/filter/math/mode.js

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
'use strict';
2+
3+
describe('modeFilter', function () {
4+
5+
var filter;
6+
7+
beforeEach(module('a8m.math.mode'));
8+
9+
beforeEach(inject(function ($filter) {
10+
filter = $filter('mode');
11+
}));
12+
13+
it('should get an array of numbers and return the mode', function() {
14+
expect(filter([1,2,3,4,5])).toEqual(1);
15+
expect(filter([2,0,2,2,2])).toEqual(2);
16+
expect(filter([1,2.32,2.32,7,5])).toEqual(2.32);
17+
expect(filter([4])).toEqual(4);
18+
});
19+
20+
21+
it('should get an !array and return it as-is', function() {
22+
expect(filter('string')).toEqual('string');
23+
expect(filter({})).toEqual({});
24+
expect(filter(!0)).toBeTruthy();
25+
});
26+
27+
});

0 commit comments

Comments
 (0)