red-array v1.0.10
Red Array
For short, array reduction. Basically, it takes an array containing any kind of data (numbers, strings, dates, functions, arrays), runs every value through a filter and creates a new array.
How it works
First, import the redArray function and the necessary filters. A filter has a support method, which checks if it is suitable for the
provided data type and a process method, which adds the value to the resulting array.
There are a couple of defined filters which can be used right away.
For example, numberRedFilter, functionRedFilter and arrayRedFilter.
The functionRedFilter will run if the provided value is a function. It will execute the function, and run the returned value through the filters again.
arrayRedFilter will run if provided value is an array. And it will recursively process it.
Example
const reduceArray = require('red-array');
const reduceArrayFilters = require('red-array/red-filters');
const filters = [reduceArrayFilters.numberRedFilter, reduceArrayFilters.functionRedFilter, reduceArrayFilters.arrayRedFilter];
const input = [1, 2, 3, 'somestring', new Date(), function() {return 4;}, [5, 6, 7, new Date(), [8, 9, 10]], function() { return function() {return 100;}}];
const result = reduceArray(input, filters);
console.log(result); // [1,2,3,4,5,6,7,8,9,10,100]
//the strings, and dates are skipped values.Creating your own filters
A filter consists of an object with 2 properties, supports and process.
If a value from an input array evaluates to true in the supports method, then the process method will be executed.
Please note: the process method is called with the context object which is an instance of RedArray class.
const myCustomFilter = {
supports: (value) => typeof value === 'string',
process(accumulator, value) {
let newVal = value + 'my custom filter';
this.acceptValue(newVal);
}
}