Some of the more complex Javascript functional programming for me to remember!
// const multiply = function(x,y) {// return x y;// }// Can be rewritten as:// const multiply = (x, y) => { return x y };// Since the function is a single expression return and braces are not needed.const multiply = (x, y) => x * y;console.log(multiply(5,10)) //50const isZero = n => n === 0;const a = [0,1,0,3,4,0];console.log(a.filter(isZero).length); // 3const getSalutation = function(hour) { var salutation; // temp value if (hour < 12) { salutation = "Good Morning";} else { salutation = "Good Afternoon"} return salutation; // mutated value}const getSalutation = (hour) => hour < 12 ? "Good Morning" : "Good Afternoon";console.log(getSalutation(10)); // Good Morning'function mapConsecutive(values, fn) { let result = []; for(let i=0; i < values.length -1; i++) { result.push(fn(values[i], values[i+1])); } return result;}const letters = ['a','b','c','d','e','f','g'];let twoByTwo = mapConsecutive(letters, (x,y) => [x,y]);console.log(twoByTwo);// [[a,b], [b,c], [c,d], [d,e], [e,f], [f,g]]let cart = [{name: "Drink", price: 3.12}, {name: "Steak", price: 45.15}, {name: "Drink", price: 11.01}];let drinkTotal = cart.filter(x=> x.name === "Drink") .map(x=> x.price) .reduce((t,v) => t +=v) .toFixed(2);console.log(Total Drink Cost $${drinkTotal}); // Total Drink Cost $14.13const convertUnits = (toUnit, factor, offset = 0) => input => ((offset + input) * factor).toFixed(2).concat(toUnit);const milesToKm = convertUnits('km', 1.60936, 0);const poundsToKg = convertUnits('kg', 0.45460, 0);const farenheitToCelsius = convertUnits('degrees C', 0.5556, -32);milesToKm(10); //"16.09 km"poundsToKg(2.5); //"1.14 kg"farenheitToCelsius(98); //"36.67 degrees C"const weightsInPounds = [5,15.4,9.8, 110];// const weightsInKg = weightsInPounds.map(x => convertUnits('kg', 0.45460,0)(x));// with curryingconst weightsInKg = weightsInPounds.map(poundsToKg);// 2.27kg, 7.00kg, 4.46kg, 50.01kg[].every(fn)[].some(fn)[].find(fn)[].filter(fn)[].map(fn)[].reduce(fn(accumulator, currentValue))[].sort(fn(a,b)) warning, mutates state![...arr].sort()[].reverse() warning, mutates state![...arr].reverse()const pipe = functions => data => { return functions.reduce( (value, func) => func(value), data );};let cart = [3.12, 45.15, 11.01];const addSalesTax = (total, taxRate) => (total * taxRate) + total;const tally = orders => pipe([x => x.reduce((total, val) => total + val), // sum the orderx => addSalesTax(x, 0.09),x => Order Total = ${x.toFixed(2)} // convert to text])(orders); // Order Total = 64.62No comments yet.
Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.