Skip to content

Instantly share code, notes, and snippets.

@vdsabev
Last active February 27, 2017 07:46
Show Gist options
  • Save vdsabev/75886494d30c5c2e0561ef60c3d2c026 to your computer and use it in GitHub Desktop.
Save vdsabev/75886494d30c5c2e0561ef60c3d2c026 to your computer and use it in GitHub Desktop.
// map
const double = x => x * 2;
map(double, [1, 2, 3]); // --> [2, 4, 6]
// filter
const isEven = x => x % 2 === 0;
filter(isEven, [1, 2, 3, 4]); // --> [2, 4]
// complement
const isOdd = complement(isEven);
find(isOdd, [1, 2, 3, 4]); // --> 1
// both / either
const wasBornInCountry = person => person.birthCountry === 'Bulgaria';
const wasNaturalized = person => Boolean(person.naturalizationDate);
const isOver18 = person => person.age >= 18;
const isCitizen = either(wasBornInCountry, wasNaturalized);
const isEligibleToVote = both(isOver18, isCitizen);
// pipelines
const multiply = (a, b) => a * b;
const addOne = x => x + 1;
const square = x => x * x;
const operatePipe = pipe(multiply, addOne, square);
operatePipe(3, 4); // => ((3 * 4) + 1)^2 => (12 + 1)^2 => 13^2 => 169
// compose
const operateCompose = compose(square, addOne, multiply);
operateCompose(3, 4); // => ((3 * 4) + 1)^2 => (12 + 1)^2 => 13^2 => 169
// partialRight
const publishedInYear = (book, year) => book.year === year;
const titlesForYear = (books, year) => {
const selected = filter(partialRight(publishedInYear, [year]), books);
return map(book => book.title, selected);
};
// curry
const publishedInYear = curry((year, book) => book.year === year);
const titlesForYear = (books, year) => {
const selected = filter(publishedInYear(year), books);
return map(book => book.title, selected);
};
// flip
const publishedInYear = curry((book, year) => book.year === year);
const titlesForYear = (books, year) => {
const selected = filter(flip(publishedInYear)(year), books);
return map(book => book.title, selected);
};
// placeholder
// middle later
const threeArgs = curry((a, b, c) => { /* ... */ });
const middleArgumentLater = threeArgs('value for a', __, 'value for c');
// only middle
const threeArgs = curry((a, b, c) => { /* ... */ });
const middleArgumentOnly = threeArgs(__, 'value for b', __);
// with the books
const publishedInYear = curry((book, year) => book.year === year);
const titlesForYear = (books, year) => {
const selected = filter(publishedInYear(__, year), books);
return map(book => book.title, selected);
};
// books with a pipeline
const publishedInYear = curry((year, book) => book.year === year);
const titlesForYear = curry((year, books) =>
pipe(
filter(publishedInYear(year)),
map(book => book.title)
)(books)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment