Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
- [shortFmt](#shortfmt)
- [byteFmt](#bytefmt)
- [kbFmt](#kbfmt)
- [median](#median)
- [Boolean](#boolean)
- [isNull](#isnull)
- [isDefined](#isdefined)
Expand Down Expand Up @@ -1223,6 +1224,17 @@ Converts kilobytes into formatted display<br/>
1 MB
1.00126 GB

```
###median
Calculates the median value of all values within an array<br/>
**Usage:** ```array | median```,
```html
<p>{{ [1,2,3,4,5] | median }}</p>
<p>{{ [2,8,2,12,2,1,5] | median }}</p>
<!--result
3
2

```
#Boolean
>Used for boolean expression in chaining filters
Expand Down
26 changes: 26 additions & 0 deletions src/_filter/math/median.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* @ngdoc filter
* @name median
* @kind function
*
* @description
* The median value of all values within an array
*/
angular.module('a8m.math.median', ['a8m.math'])
.filter('median', ['$filter', function ($filter) {
return function (input) {
var orderedArray = $filter('orderBy')(input);

if(!isArray(input)){
return input;
}

var medianIndex = parseInt(orderedArray.length / 2);

if(orderedArray % 2 != 0){
medianIndex++;
}

return orderedArray[medianIndex - 1];
}
}]);
1 change: 1 addition & 0 deletions src/filters.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ angular.module('angular.filter', [
'a8m.math.byteFmt',
'a8m.math.kbFmt',
'a8m.math.shortFmt',
'a8m.math.median',

'a8m.angular',
'a8m.conditions',
Expand Down
25 changes: 25 additions & 0 deletions test/spec/filter/math/median.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
'use strict';

describe('medianFilter', function () {

var filter;

beforeEach(module('a8m.math.median'));

beforeEach(inject(function ($filter) {
filter = $filter('median');
}));

it('should get an array of numbers and return the median one', function() {
expect(filter([1,2,3,4,5])).toEqual(3);
expect(filter([2,8,2,12,2,1,5])).toEqual(2);
expect(filter([1])).toEqual(1);
});

it('should get an !array and return it as-is', function() {
expect(filter('string')).toEqual('string');
expect(filter({})).toEqual({});
expect(filter(!0)).toBeTruthy();
});

});