JSFiddle - React, Tailwind, and code Playground
Babel + JSX
/*
* I find Javascript very elegant.
*
* Nowadays I try to write only functions that
* are a few lines long and do not need a semi-colon
* because everything is just composed.
*
* Composition, immutability, absence of side effects.
* Point-free programming.
* I find this appeasing.
*
* It's a fun and rewarding challenge to convert a huge function to
* this form. Fewer bugs and peace of mind.
*
*/
const isIterable = a =>
a && typeof a === 'object' && (typeof a[Symbol.iterator] === 'function')
const flatMap = fn => list => [].concat(...list.map(fn))
console.log(
flatMap(x => [x, x, x])([1, 2, 3])
) // [1, 1, 1, 2, 2, 2, 3, 3, 3]
const deepFlatMap = fn => flatMap(
a => ( isIterable(a) ? deepFlatMap(fn)(a) : fn(a) )
)
console.log(
deepFlatMap(x => [x, x])([[1, [2, 3]], 4, [[[5]], 6]])
) // [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6]
const flatten = deepFlatMap(x => x);
const sum = (...list) => flatten(list).reduce((s, value) => s + value, 0)
console.log(
sum(1, [2, 3, [[[4]]], 5])
) // 15