1.1.2 • Published 8 years ago

lodash-bound v1.1.2

Weekly downloads
623
License
MIT
Repository
github
Last release
8 years ago

lodash-bound

Enables chained lodash functions with ES bind (::) syntax

build status npm version codeclimate

babel-plugin-lodash and lodash-webpack-plugin introduced an optimizaion that includes only the used lodash methods in the compiled webpack file. So you can still import _ from 'lodash' without having the entire lodash library to load.

However, chaining is not supported. _.chain(value).method() or _(value).method() will result in an (understandable) error.

That error links to this article which suggests using lodash/fp in order to maintain somwhat chained syntax.

With the new ES bind syntax, ::, it's now possible to 'chain' a method to an object, as if it was on its prototype.

function upcase() { return this.toUpperCase() }
function shout(n) { return this + '!'.repeat(n) }
console.log('hello'::upcase()::shout(5)) // => HELLO!!!!!

This library wraps all lodash methods with functions that consider this as the value, because lodash methods take a value as a first argument, which wouldn't fit the :: syntax.

Each method requires only the single corresponding file from lodash, so no unnecessary sources are being added to the output.

Installation

npm install lodash-bound --save

Requires also babel-preset-es2015 and babel-preset-stage-0 babel presets.

Usage

import _map from 'lodash-bound/map'
import _filter from 'lodash-bound/filter'
import _groupBy from 'lodash-bound/groupBy'
import _mapValues from 'lodash-bound/mapValues'

let arr = [
  { id: 'm1', conversationId: 'c1', body: 'hello', read: true },
  { id: 'm2', conversationId: 'c1', body: 'world', read: false },
  { id: 'm3', conversationId: 'c2', body: 'foo', read: false },
  { id: 'm4', conversationId: 'c2', body: 'bar', read: false }
]

let unreadBodyByConversationId = arr
  ::_filter({ read: false })
  ::_groupBy('conversationId')
  ::_mapValues(x => x::_map('body'))

# => { c1: [ 'world' ], c2: [ 'foo', 'bar' ] }

Note: Webpack 2 will support 'tree-shaking' which eliminates unused requires. This will allow requiring all methods in one statements: import { _map, _filter, _groupBy, _mapValues } from 'lodash-bound', without requiring all the rest of the methods.

Test

npm install
npm test

License

MIT