R
E
A
C
T
O
xamples
epeat
ode
pproach
ptimize
est
{Custom Array Filters}
The Question
Barack Obama has a lot of data he is required to apply filters to, which is simple enough, but he wants a shorter way of doing so.
He wants the following functions to work as expected:
even // [1,2,3,4,5].even() should return [2,4]
odd // [1,2,3,4,5].odd() should return [1,3,5]
under // [1,2,3,4,5].under(4) should return [1,2,3]
over // [1,2,3,4,5].over(4) should return [5]
inRange // [1,2,3,4,5].inRange(1,3) should return [1,2,3]
Catches
They should also work when used together, for example:
[1,2,18,19,20,21,22,30,40,50,100].even().inRange(18,30) // should return [18, 20, 22, 30]
And finally the filters should only accept integer values from an array, for example:
["a", 1, "b", 300, "x", "q", 63, 122, 181, "z", 0.83, 0.11].even() // should return [300, 122]
Key Concepts
1. Arrays are also objects that have some special methods inherited from the Array.prototype global Object.
2. JavaScript Arrays are not real arrays. Instead , they are objects with unique integer keys.
var arr = [];
var arr2 = [1, "Hi", {a:2}, function () {console.log('boo');}];
var arr3 = new Array();
var arr4 = new Array(1,"Hi", {a:2}, function () {console.log('boo');});
3. 'this' can be your new best friend or your worst nightmare
Test Cases
1. Floating point
2. strings
3. negative numbers
[.45,.3777778, 23.12, 3333.6, 98.199, 4.4, 1.1]
['3','4','34','222222', '12', '23']
[-1,-4,-6,-7,-4,-8,-9,-22,-88]
Answer
Array.prototype.isInt = function() {
return this.filter(function(n) { return (typeof(n)==='number') && (n% 1 === 0) });
}
Array.prototype.even = function() {
return this.isInt().filter(function(n) { return n%2===0 });
}
Array.prototype.odd = function() {
return this.isInt().filter(function(n) { return n%2!== 0 });
}
Array.prototype.under = function(x) {
return this.isInt().filter(function(n) { return n < x });
}
Array.prototype.over = function(x) {
return this.isInt().filter(function(n) { return n > x });
}
Array.prototype.inRange = function(min, max) {
return this.isInt().filter(function(n) { return n >= min && n <= max });
}
Conclusion
Arrays are objects and objects are cool!
Custom Array Filters
By es1831
Custom Array Filters
- 2,373