Skip to content

Commit

Permalink
feat(util): isolate lodash instance on collection
Browse files Browse the repository at this point in the history
util manages an isolated instance of lodash to wrap collections and exposes a method to add mixins
to the same instance.
  • Loading branch information
thetutlage committed Feb 18, 2016
1 parent 56ed7e5 commit 90a3ba5
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
31 changes: 30 additions & 1 deletion lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const i = require('inflect')
const _ = require('lodash')
const humanize = require('humanize-number')
const util = exports = module.exports = {}
const isolatedLodash = _.runInContext()

/**
* makes table name from a class defination
Expand Down Expand Up @@ -84,7 +85,35 @@ util.pick = function (values, valuesToOmit) {
* @public
*/
util.toCollection = function (values) {
return _(values)
return isolatedLodash(values)
}

/**
* returns isolated instance of lodash, it is also
* used while wrapping values in a collection.
*
* @method lodash
*
* @return {Object}
*/
util.lodash = function () {
return isolatedLodash
}

/**
* adds a mixin to the lodash instance
*
* @method addMixin
* @param {String} name
* @param {Function} method
* @param {Object} extra
*
* @public
*/
util.addMixin = function (name, method) {
const mixin = {}
mixin[name] = method
isolatedLodash.mixin(mixin)
}

/**
Expand Down
8 changes: 8 additions & 0 deletions test/unit/util.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

/* global describe, it*/
const util = require('../../lib/util')
const _ = require('lodash')
const chai = require('chai')
const expect = chai.expect

Expand Down Expand Up @@ -112,4 +113,11 @@ describe('Utils', function () {
const meta = util.makePaginateMeta(20, 1, 10)
expect(meta).deep.equal({total: 20, perPage: 10, currentPage: 1, lastPage: 2, data: []})
})

it('should add a mixin to lodash isolated instance', function () {
const foo = function () {}
util.addMixin('foo', foo)
expect(_.isFunction(_.foo)).to.equal(false)
expect(_.isFunction(util.lodash().foo)).to.equal(true)
})
})

0 comments on commit 90a3ba5

Please sign in to comment.