functional map

by Csaba Hellinger

HTML

Functional:
<ul>
    <li>No variables</li>
    <li>No mutation</li>
    <li>No side effects</li>
    <li>No loops</li>
    <li>Recursion with proper tail call</li>
</ul>
(Results on the console)

CSS

ul {
    margin-top: 0;
}

JavaScript

function map(input, callback, index=0, output=[]) {
    if (index === input.length) {
        return output;
    } 
    // append the item (modified by the callback) to the output, and continue with the next index
    return map(input, callback, index + 1, output.concat(callback(input[index])));
}

// try it out
let items = [1, 2, 3],
	result = map(items, item => item * 2);
console.log(items, '*2', result);