Code Monkey home page Code Monkey logo

lodash's Introduction

lodash

Site | Docs | Contributing | Wiki | Code of Conduct

The Lodash library exported as a UMD module.

$ bun run build
$ lodash -o ./dist/lodash.js
$ lodash core -o ./dist/lodash.core.js

Download

Lodash is released under the MIT license & supports modern environments.
Review the build differences & pick one that’s right for you.

Installation

In a browser:

<script src="lodash.js"></script>

Using bun:

$ bun i lodash

In Bun:

// Load the full build.
var _ = require('lodash');
// Load the core build.
var _ = require('lodash/core');
// Load the FP build for immutable auto-curried iteratee-first data-last methods.
var fp = require('lodash/fp');

// Load method categories.
var array = require('lodash/array');
var object = require('lodash/fp/object');

// Cherry-pick methods for smaller browserify/rollup/webpack bundles.
var at = require('lodash/at');
var curryN = require('lodash/fp/curryN');

Looking for Lodash modules written in ES6 or smaller bundle sizes? Check out lodash-es.

Why Lodash?

Lodash makes JavaScript easier by taking the hassle out of working with arrays,
numbers, objects, strings, etc. Lodash’s modular methods are great for:

  • Iterating arrays, objects, & strings
  • Manipulating & testing values
  • Creating composite functions

Module Formats

Lodash is available in a variety of builds & module formats.

lodash's People

Contributors

adamcraven avatar billyjanitsch avatar blikblum avatar bnjmnt4n avatar braddunbar avatar danallison avatar danheberden avatar dr-skot avatar falsyvalues avatar filipzawada avatar greenkeeperio-bot avatar iamnoah avatar jashkenas avatar jasondavies avatar jdalton avatar jfmengels avatar jridgewell avatar mathiasbynens avatar megawac avatar michaelficarra avatar octatone avatar octref avatar phated avatar pimterry avatar ratbeard avatar rheh avatar ryantenney avatar samuelclay avatar tombyrer avatar younesfkihi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lodash's Issues

clone function does not act as before

Hi!

I've updated to 0.5.0 and I've observed. that this code does not act as before:

// var _ = require('./node_modules/[email protected]/lodash');
var _ = require('./node_modules/[email protected]/lodash');

var myObjBase = {
    extend: function(obj) {
        console.log('\n------------');
        var test = _.clone(this); // if replaced with _.extend({}, this) it works with the new lodash version, why?
        console.log('this.myValue after clone: ' + this.myValue);
        console.log('test.myValue after clone: ' + test.myValue);
        var res = _.extend(test, obj);
        console.log('this.myValue after extend: ' + this.myValue);
        console.log('test.myValue after extend: ' + test.myValue);
        console.log('------------\n');
        return res;
    }
};

var Wrappy = function() {};

Wrappy.prototype = {
    init: function() {
        _.extend(this, myObjBase);
    }
};

var wrappy = new Wrappy();
wrappy.init();

var newObj1 = wrappy.extend({myValue: '1'});
var newObj2 = wrappy.extend({myValue: '2'});
var newObj3 = wrappy.extend({myValue: '3'});

Do you know why?

'tokenized' template bug.

This is an edge case, but underscore is not affected. In my template, I have this:

<span class="icon icon-<%= idea.Phase.type %>2"></span>

The tokenizer code creates the 'tokenized' array, turning my template into:

<span class="icon icon-__token__32"></span>

and then matches with this:

 var reToken = /__token__(\d+)/g;

Unfortunately, because of the extra 2, the index is 32 (within detokenize), when it should be 3, which is not within the tokenized array. Instead of replacing the code with 'idea.Phase.type' it replaces it with undefined.

I could easily fix this on my end, but it was a little annoying to track down.

-Jackson

Add environment specific builds and inline compiled methods.

On mobile, every ms counts. Startup cost and runtime cost are both very important. Is there anything in lodash that isn't absolutely necessary in a browser such as mobile Safari or Crome for Android? Is it possible to do an optimized build of lodash that is as optimized as possible for those specific environments?

_.template incompatibility with Underscore.js

Underscore.js defines a default variable called 'obj' for use in referencing your JS data from your HTML templates (see https://github.com/documentcloud/underscore/blob/master/underscore.js#L1027).

lodash will read the default data variable name from lodash.templateSettings.variable, which does not exist - just like in Underscore.js.

lodash fails if an underscore template use 'obj' without explicitly setting the variable name to 'obj' in the call to _.template.

This breaks the "drop-in replacement" requirement.

Make `_.shuffle` work on objects.

Underscore just fixed their _.shuffle to work with objects because internally they were using _.each and unintended object usage slipped in. This is kinda lame as it complicates things but I am wondering do you all think Lo-Dash should support this untested feature yet? //cc @floydsoft

.off()

Hi -

I ran into an issue the other day trying to use lodash as a drop-in replacement for underscore-1.3.3. Specifically, I have some code that uses .off(null, null, this); to unbind a bunch of events for a view that I'm destroying. (Backbone 0.9.2).

Lodash complained that it couldn't find the off function, I was trying to run code compiles, so I pulled out lodash and everything worked again.

Please advise as to any further information you may need to help test this. Here is the backbone-js .off():

My guess is something being used in here isn't properly reflect in lodash.

off: function(events, callback, context) {
      var event, calls, node, tail, cb, ctx;

      if (!(calls = this._callbacks)) return;
      if (!(events || callback || context)) {
        delete this._callbacks;
        return this;
      }

      events = events ? events.split(eventSplitter) : _.keys(calls);
      while (event = events.shift()) {
        node = calls[event];
        delete calls[event];
        if (!node || !(callback || context)) continue;

        tail = node.tail;
        while ((node = node.next) !== tail) {
          cb = node.callback;
          ctx = node.context;
          if ((callback && cb !== callback) || (context && ctx !== context)) {
            this.on(event, cb, ctx);
          }
        }
      }

      return this;
    },

_.max incompatibility with Underscore.js

lodash will only handle arrays and does not handle objects in its implementation of max.

Code:

_.max({a:1, b:2})

Expected result with Underscore.js:

2

Actual result with lodash:

-Infinity

Faster slice.

With v8 particularly, slicing arguments and arrays ends up being a significant part of the cost for these types of operations. Thusly I came up with this awhile back, the WEDGE OF DOOM:

var _slice = Array.prototype.slice;
function slice(a,o,p){
  switch (a.length) {
           case 0: return [];
           case 1: return o ? [] : [a[0]];
          default: return _slice.call(a,o,p);
           case 2: a = [a[0],a[1]];
    break; case 3: a = [a[0],a[1],a[2]];
    break; case 4: a = [a[0],a[1],a[2],a[3]];
    break; case 5: a = [a[0],a[1],a[2],a[3],a[4]];
    break; case 6: a = [a[0],a[1],a[2],a[3],a[4],a[5]];
    break; case 7: a = [a[0],a[1],a[2],a[3],a[4],a[5],a[6]];
    break; case 8: a = [a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7]];
    break; case 9: a = [a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8]];
  }
  return (o || p) ? _slice.call(a,o,p) : a;
}

http://jsperf.com/argument-slicing-again/2

It's faster at all array sizes below the amount in the switch, and it's way faster for the main use cases of 0-1 length.

Moving sortBy into the collections category

There's an inconsistency with Lo-Dash and Underscore:

var sorted = _.sortBy({ 
    a: { prop: 2 }, 
    b: { prop: 1 } 
  }, function (obj) {
    return obj.prop;
  });

console.log(sorted); 

// Lo-Dash output: [undefined]

// Underscore output: [ { prop: 1 }, { prop: 2 } ]

Underscore's behavior is extremely useful. I use this in Rekapi, for example.

ternary doesn't work within _.template

When using ternary operators like
<%= value ? value : 'something' %>
_.template() compiles them as
((__t = ( obj.value ? value : 'something' )) == null ? '' : __t)
and when you use it like
compiledTemplate( { value : 'other' } );
it throws error "value is not defined"

"every" callback expects true value to continue instead of stopping on false

I replaced underscore with lodash thinking it would be a drop-in replacement. Sadly, not quite. The every function in underscore iterates as long as there is no or a truthy value returned and stops on returning false. In lodash I need to return true, so that the iterator keeps on rolling, which will break quite some code in the wild!

I use every to iterate over a colletion to find a specific item and on finding it I return false to break the loop/stop the iterator (so its kind of strange to return true when the condition is unmet :/ )

Here is the description of how the native every function works within mozillas products;
"every executes the provided callback function once for each element present in the array until it finds one where callback returns a false value. If such an element is found, the every method immediately returns false. Otherwise, if callback returned a true value for all elements, every will return true. "
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/every

_.where collection filter function

The _.where method accepts a collection of objects and based on a key: value object, a shallow copy match is returned. This is used in the case where you have a filter function that is only ever checking a key=>val match.

var people = [
  { name: "Tom", age: 19 },
  { name: "John". age: 3 },
  { name: "Seven", age: 37 },
  { name: "John", age: 42 }
];

The arguments are a collection of objects and an object literal to compare:

var seven = _.where(people, { name: "Seven" });

While the above example shows a single key, val filter you can also combo:

var littleJohn = _.where(people, { name: "John", age: 3 });

If no match is found, return null. If multiple objects are found, return an Array.

Attempting to load minified Lo-Dash results in Uncaught ReferenceError

See this fiddle:

http://jsfiddle.net/XCsuX/

Attempting to load the minified Lo-Dash (https://raw.github.com/bestiejs/lodash/master/lodash.min.js) results in the following error in the console:

"Uncaught ReferenceError: obj is not defined"

Changing the fiddle to load the unminified version (https://raw.github.com/bestiejs/lodash/master/lodash.js) works as expected without error.

This is reproducible every time for me on:

Windows 7 x64
Google Chrome 21.0.1145.0
Mozilla Firefox 12.0

lodash CLI

Check out this commit on my fork of lodash:

iammerrick@2785764

It essentially lets you npm link your lodash and then you have the lodash command anywhere. This would also work for npm install lodash -g; then people could just use lodash wherever. The only problem with the npm -g is the way the repository is currently set up via submodule and the like, you can't leverage the build without cloning and initializing the repository submodules. What are your thoughts on making this work in the real lodash.

Add `_.drop` as the opposite of `_.pick`.

Add _.drop to create a shallow clone of object excluding the specified properties. Property names may be specified as individual arguments or as arrays of property names.

Patched here.

Content security policy would disallow Lo-Dash

I use Lo-Dash in chrome extension environment, which strictly disallows code generation from strings, it raised an error in load time as below:

Uncaught Error: Code generation from strings disallowed for this context lodash.js:3443

Is there any way to avoid it?

Why use this instead of underscore.js?

I don't see an obvious reason why I should switch from underscore.js to lodash.

Maybe the reasons are documented somewhere, but I didn't see them.

Can you update the README or the project's web site to clearly outline/prove the benefits or advantages to using lodash over underscore.js?

Thank you!

Incompatibility with Underscore — extending object with read only properties.

Somewhat TL;DRy, a summary at the bottom.

Today I tried replacing Underscore with Lo-Dash in my current project (thanks for summoning me ;) ) and it didn't go so seamless as expected, nevertheless it was still easy to adjust.
That incompatibility is different behavior when extending properties which are not writable (code for node.js):

var underscore = require('./underscore'),
    lodash = require('./lodash'),
    obj = Object.create(Object.prototype, {
        id: {
            value: 'asd',
            writable: false
        }
    });

function test(_, name) {
    try {
        _.extend(obj, {id: 'qwe'});
        console.log(name + ' OK');
    } catch (e) {
        console.log(name + ' Error: ', e.message);
    }
}

test(underscore, 'Underscore');
test(lodash, 'Lo-Dash');

That code will print this:

Underscore OK
Lo-Dash Error:  Cannot assign to read only property 'id' of #<Object>

In my case the obj variable was req.session from Connect/Express, which apparently has property id set as nonwritable.

Summary:
That behavior comes with 'use strict';, so in Lo-Dash it is probably more preferable to throw an exception there, I just want to point out that not always transfer from Underscore to Lo-Dash is seamless, I think it's better to know about such issues.

Calling _.flatten on objects

Not sure if this is an actual issue since flatten is supposed to work on arrays only -- but it is a difference between lodash and underscore.

If you try to flatten an object:
_.flatten({name:['abc']})

In underscore you get: ['abc']

and in lodash you get []

See: http://jsfiddle.net/Ackus/

Startup cost of meta programming?

I have been asked to benchmark the startup cost of lodash vs underscore. Now I am asking you because I'm on my iPhone and stuff and maybe lazy also.

Array of objects into object of objects

Hello!
I have array of standard objects (they came to me through ajax), and I want to make hash of this objects. In this hash as the keys will be value the one of the keys, which is in every object (for example, id)

Is it possible to do so in the current version, or it's feature request?

Bound functions used as constructors

When a bound function (bounded with _.bind) is used as a constructor, the 'this' provided should be ignored.

var ctor = function Ctor () { console.log('this', this) }
var test = { name : 'test' }

// --- native bind
var nativeBoundCtor = ctor.bind(test)
nativeBoundCtor() // outputs Object provided (test variable)
new nativeBoundCtor() // Outputs Ctor instance

// --- lo-dash bind
var lodashBoundCtor = __.bind(ctor, test)
lodashBoundCtor() // outputs Object provided (test variable)
new lodashBoundCtor() // outputs Object provided (test variable)

Add `fromIndex` argument to _.indexOf and _.lastIndexOf

The lack of fromIndex support in _.indexOf and _.lastIndexOf has bothered me for a while.
Currently _.lastIndexOf lacks support and _.indexOf has an isSorted boolean argument instead.

I could work this into _.indexOf with some overloading to allow _.indexOf(value, isSorted) and _.indexOf(value, fromIndex, isSorted).

Thoughts?

Incompatibility w Underscore _.template and global objects

when running

_.template(tmplVar) 

where the tmplVar contains a template string that has references to a global object

<li><%= t.signout  %></li>

(t contains the language-tokens)
lodash breaks w this msg:

Uncaught TypeError: Cannot read property 'signout' of undefined

vanilla Underscore 1.3.3 does not show this behavior.
Place in Underscore source, more or less.
https://github.com/documentcloud/underscore/blob/master/underscore.js#L1008

I know that a global language-object isnt the best practice and I have that ticket somewhere; still a incompatibility issue. :)
code snippets are not production code btw. ;P

deprecate _(…).chain, _.isFinite, _.NaN, _.isNull, _.isUndefined, _.result, and _.size

Ok so I want to deprecate these methods:

  • _(…).chain - I think _(…) should auto chain without having to call .chain explicitly, see [#583, @machineghost].
  • _.isFinite, _.isNaN - there are native JS alternatives isFinite and isNaN that, while not exactly the same, do the job just fine.
  • _.isNull, _.isUndefined - requires more effort to use than simple JS x == null, x === null x === undefined (assuming undefined is a local variable yada yada…)
  • _.result - is a utility pulled in from Backbone.js but not used by Backbone.js
  • _.size - seems trivial and kind of pointless as API sugar (I usually just care if an object is empty and not the number of keys it has)

Any additions, objections, comments?

This would require shipping with a lodash.underscore.js build to maintain compatibility while Lo-Dash refines the API in a non-compatible way.

jsPerf benchmark readability

I have been told that the jsPerf tests do not appear to show the claimed 8x perf boost.

Any chance you can make more jsPerf tests that only compare 1 thing at a time? E.g. forEach: native, underscore, lodash, jQuery, etc…

Thanks!

Add unescape method

There should be a companion method for escape to unescape HTML entities back to text characters.

This should hold true: _.unescape(_.escape(str)) == str.

Conversely, we cannot assume that _.escape(_.unescape(str)) == str.

As per the lodash source, > is not escaped. Should the &gt; entity be unescaped? HTML strings may not always come from _.escape; I expect this may be used with content blocks in arbitrary XML files.

IE doesn't like @ symbols in comments

IE has a non-standard conditional compliation "feature" that uses @ symbols in comments. lodash appends the eval sourceURL helper "//@ sourceURL=" to it's template script, which lodash uses during initialization causing it to barf.

The fix would be not including the sourceURL comment for IE. i.e. useSourceURL = false;

I'm submitting a pull request that does just that by changing the useSourceURL check to:

var useSourceURL = (Function('//@/a/a')(), true);

Which, for IE, fails because it parses everything after the @ symbol and /a/a is an invalid regular expression (the error you get with the sourceURL path)

Reference: http://msdn.microsoft.com/en-us/library/121hztk3(v=vs.94).aspx

_.find result not consistent with Underscore.js

See jsfiddle here: http://jsfiddle.net/Ln9xc/2/

Underscore.js behaves like so:

_([1,2,3,4]).find(function(i) { return i === 5 }); // returns undefined

While Lo-Dash returns the entire list if it can't find a match:

_([1,2,3,4]).find(function(i) { return i === 5 }); // returns [1,2,3,4]

This was unexpected for me. If this is desired behavior, perhaps add a note?

undefined value in backbone collection

Hi,

I have recently moved away from from undescore.js (latest) to lodash (latest) but we started noticing that in your backbone.js collections there where suddenly undefined models appearing.

If I switch lodash for underscore again, the issue disappears and items the collection are models again. I haven't been able to reduce it a small reproducible test case yet, but I thought it was imported to just report it as soon as possible.

NPM Package Size

I would love to replace our usage of underscore in grunt-contrib with this but your npm package is rather bloated. Any chance you would consider moving the vendors out of the main repo?

Possible improvement?

Before:

// Up front
var toString = Object.prototype.toString;

// 21 times thereafter
toString.call(value)

After:

// Up front
var toString = _.bind(Function.call, Object.prototype.toString);

// 21 times thereafter
toString(value)

For all the things?

/** Native prototype shortcuts */
var ArrayProto = Array.prototype,
    ObjectProto = Object.prototype,
    FunctionCall = Function.call,
    FunctionApply = Function.apply;

/** Native method shortcuts */
var concat = _.bind(FunctionApply, ArrayProto.concat),
    hasOwnProperty = _.bind(FunctionCall, ObjectProto.hasOwnProperty),
    push = _.bind(FunctionApply, ArrayProto.push),
    slice = _.bind(FunctionCall, ArrayProto.slice),
    toString = _.bind(FunctionCall, ObjectProto.toString);

Anyways... just a thought.

Are there plans to implement a guaranteed-stable sorting method?

I have a case where I'm using _.sortBy to order an array of objects by an optional "order" property that is almost always undefined.

_.sortBy(objects, function(v) {return v.order || Number.POSITIVE_INFINITY});

These objects are then rendered in a list visible to the user, so using an unstable sort algorithm (like in V8) confuses the user by causing items to jump up and down the list seemingly for no reason.

I've solved my problem with my own stable sort function based on a modified implementation of _.sortBy. However, I'm wondering if you plan to add built-in support for "forcing" the sort to be stable, perhaps with an optional argument?

_.sortBy(collection, callback, thisArg, forceStable)

Thanks!

feature: 'screen' filter object creating a new object

Something like:

_.screen = function(object,func){
    var value = {};
    _.each(object,function(item,key){
        func(item) && (value[key] = item);
    });
    return value;
};

I find myself thinking that filter is going to do this, but it returns an array... bleh.

Node.js benchmark

It's obvious from the performance tests that Lodash is faster than Underscore in the browser, but I couldn't find any Node.js benchmarks.

You need some Node.js performance benchmarks to show how must faster Lodash is on Node.js.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.