Last active
March 16, 2016 18:35
-
-
Save Nitive/763c1dbfc6a80025b0a1 to your computer and use it in GitHub Desktop.
function wrap to chain lodash/underscore/whatever functions with plain js class methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { compact, uniq, take } from 'lodash' | |
const wrap = function (fn, ...args) { | |
return fn(this, ...args) | |
} | |
const exampleData = [ | |
{ date: '03/12/2012', text: '12 марта' }, | |
{ date: '03/13/2012', text: '13 марта' }, | |
{ date: '04/12/1961', text: '12 апреля' }, | |
null, | |
{ date: '06/22/2014', text: '12 июля' }, | |
] | |
const getDateProp = obj => obj.date | |
const getYear = dateString => (new Date(dateString)).getFullYear() | |
// before: | |
// hard to read and understand | |
// const result = take(uniq(compact(exampleData).map(getDateProp).map(getYear)).sort(), 2) | |
// after: | |
// readable and easy to understand | |
// customisable | |
const result = exampleData | |
::wrap(compact) | |
.map(getDateProp) | |
.map(getYear) | |
::wrap(uniq) | |
.sort() | |
::wrap(take, 2) | |
console.log(result) // [1961, 2012] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment