30
loading...
This website collects cookies to deliver better user experience
Pointfree style is also known as tacit programming by its champions, or as Pointless Programming by its detractors!
const testOdd = x => x % 2 === 1;
const testUnderFifty = x => x < 50;
const duplicate = x => x + x;
const addThree = x => x + 3;
const myArray = [22, 9, 60, 24, 11, 63];
const a0 = myArray
.filter(testOdd)
.map(duplicate)
.filter(testUnderFifty)
.map(addThree);
// [ 21, 25 ]
.filter(x => x % 2 === 1)
-- this is pointfree style! The resulting code is more compact, and simpler to read: "keep only odd numbers, duplicate all, keep numbers under 50, finally add 3 to all".const pipeline = (...fns) => fns.reduce((result, f) => (...args) => f(result(...args)));
const map = fn => arr => arr.map(fn);
map(...)
function is a curried version of the .map(...)
method, more suitable for functional programming purposes.const separateStringIntoWords = (str) => str.split(" ");
const firstToUpper = (str) => str[0].toUpperCase() + str.slice(1).toLowerCase();
const joinWordsIntoString = arr => arr.join(" ");
const makeTitleCase = pipeline(separateStringIntoWords, map(firstToUpper), joinWordsIntoString);
makeTitleCase(...)
as follows.makeTitleCase("GO TO sTaTeMeNt conSIDered HARMful");
// "Go To Statement Considered Harmful"
const makeTitleCase2 = (str) => str.split(" ").map(word => word[0].toUpperCase() + word.slice(1).toLowerCase()).join(" ");
makeTitleCase2("GO TO sTaTeMeNt conSIDered HARMful");
// "Go To Statement Considered Harmful"
makeTitleCase(...)
can be seen as correct by understanding that you apply three functions: one that (very likely!) takes a string and separates into words, then a second one that maps each word by making its first letter uppercase, and a final one that makes a string out of several words. Those auxiliary functions will probably be used elsewhere, so that's not a waste. And, I believe that the extra clarity compensates the possibly longer code.const numbers = [22,9,60,12,4,56]
numbers.map(Number.parseFloat); // [22, 9, 60, 12, 4, 56]
numbers.map(Number.parseInt); // [22, NaN, NaN, 5, NaN, NaN]
numbers.map((x) => parseInt(x)); // [22, 9, 60, 12, 4, 56]
const unary = fn => (...args) => fn(args[0]);
numbers.map(unary(Number.parseInt)); // [22, 9, 60, 12, 4, 56]