Proposal: mapRight
Overview:
The proposal presents mapRight, an array method that processes elements from right to left, analogous to how reduceRight complements reduce.
Currently, JavaScript provides map to iterate over an array from left to right. However, there is no built-in method to map elements in reverse order. When engineers need to achieve this, they typically reverse the array first and then apply map, leading to an unnecessary O(n) time complexity due to the additional array reversal.
Reasoning:
map: iterates from left to right
reduce: iterates from left to right
reduceRight: iterates from right to left
However, there is no mapRight counterpart to map that performs mapping from right to left.
Engineers often work around this by manually reversing the array before calling map. For example below:
const arr = [1, 2, 3, 4, 5];
const result = arr.toReversed().map(x => x + 1); // [6,5,4,3,2]
This introduces an extra linear time and space complexity i.e. O(N) operation and might be inefficient for data intensive applications like AI.
We could also use reduceRight to be forced to behave like mapRight, it is not ideal solution.
Although engineers can achieve the same result using a for loop, but it is less readable in function style code. Introducing mapRight enhances readability and expressiveness by providing a more declarative approach.
Proposal:
Proposal is to introduce Array.prototype.mapRight, which behaves like map, but processes elements from right to left.
array.mapRight(callbackFunction(element, index, array), thisArg)
const arr = [1, 2, 3, 4, 5];
const result = arr.mapRight (x => x + 1);
console.log(result); // [6,5,4,3,2]
The callback function receives the same parameters as map:
- element β The current element being processed in the array.
- index β The index of the current element being processed in the array.
- array β The array mapRight was called upon.
Many AI applications, such as time-series data processing, NLP, and neural networks, require reverse-order traversal.
Advantages:
- Eliminates the need for .reverse() or .toReversed(), saving O(N) complexity.
- Provides a direct functional counterpart to map, just as reduceRight
Conclusion:
Integrating mapRight into JavaScript will enhance efficiency and readability when processing arrays from right to left.