I'm recreating the filter, map, find functions in js. And I have a function pipe, that takes the given array and passes it trough an array of functions such as filter, map etc.
These are my functions:
const filter = (arr, callback) => {
let newArr = [];
let j = 0;
for (let i = 0; i < arr.length; i++) {
if (callback(arr[i])) {
newArr[j] = arr[i];
j++;
}
}
return newArr;
};
const map = (arr, callback) => {
let newArr = [];
for (let i = 0; i < arr.length; i++) {
newArr[i] = callback(arr[i], i);
}
return newArr;
};
const pipe = (arr, callbacks) => {
console.log(arr, "arr");
console.log(callbacks, "callbacks");
};
I can use filter like so, and the function works fine.
const arr = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']
filter(arr, item => item.length > 6) // returns ["exuberant", "destruction", "present"]
However, when using pipe, I should not pass arr to each function. Instead filter and map should somehow take arr from pipe. But since those functions are being called directly in the pipe call, I do not see how can I achieve that functionality.
const arr = ['spray', 'limit', 'elite', 'exuberant', 'destruction']
pipe(
arr,
[
filter(item => item.length > 6), // returns ["exuberant", "destruction"]
map((item, index) => ({ id: index, name: item })) // returns [{ id: 0, name: 'exuberant' }, { id: 1, name: 'destruction' }]
]
)
// pipe returns [{ id: 0, name: 'exuberant' }, { id: 1, name: 'destruction' }]
Usually filter and map takes 2 params, arr and a callback. But in pipe it takes just the callback.
Any help would be appreciated. Thanks.