Skip to content

Instantly share code, notes, and snippets.

@classmember
Created August 27, 2018 15:24
Show Gist options
  • Save classmember/6c9ade81883d311899543af2c60dca88 to your computer and use it in GitHub Desktop.
Save classmember/6c9ade81883d311899543af2c60dca88 to your computer and use it in GitHub Desktop.
const { map, filter, reduce } = require('lodash');
// array from 0 to 9
const data = [0,1,2,3,4,5,6,7,8,9];
// helper functions
const doubled = val => val * 2;
const isEven = val => val % 2;
const isOverTen = val => val >= 10;
// multi-variable helper function
const totaled = (total, n) => total + n;
// functional
const mapped = data.map(doubled); // 0,2,4,6,8,10,12,14,16,18
const filtered = data.filter(isEven); // 1,3,5,7,9
const reduced = data.reduce(totaled); // 45
// chained functional calls
const map_filter_reduce = data.map(doubled)
.filter(isOverTen)
.reduce(totaled); // 75
// output
console.log(`mapped: ${mapped}`); // mapped: 0,2,4,6,8,10,12,14,16,18
console.log(`filtered: ${filtered}`); // filtered: 1,3,5,7,9
console.log(`reduced: ${reduced}`); // reduced: 45
console.log(`map_filter_reduce: ${map_filter_reduce}`); // map_filter_reduce: 70
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment