lodash / lodash Goto Github PK
View Code? Open in Web Editor NEWA modern JavaScript utility library delivering modularity, performance, & extras.
Home Page: https://lodash.com/
License: Other
A modern JavaScript utility library delivering modularity, performance, & extras.
Home Page: https://lodash.com/
License: Other
Make lodash build and unit tests work when used as a node package.
This means using the package.json dependencies property and removing the use of submodules.
I've already added a scripts
entry to the package.json and prepped the build script to use process.cwd()
.
// cc @strk @iammerrick
See this fiddle:
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
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?
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.
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.
Looks like a small issue with the script you're using on the site to render markdown:
http://lodash.com/docs#memoize (in the code example)
<
should be <
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?
I think you should know :)
_.drop({ 'name': 'moe', 'age': 40, 'userid': 'moe1' }, 'userid');
returns: []
I checked LoDash's compatibility with Backbone by running the unit tests provided with Backbone with LoDash. I have found that it failed one of the unit tests.
Unit Tests:
https://github.com/documentcloud/backbone/tree/master/test
Unit Test Error:
http://imageshack.us/photo/my-images/843/lodasherror.png/
I couldn't find this info on the readme or the website, I think it should be somewhere.
Hi All.
You all are summoned here because I've fixed, in Lo-Dash, various Underscore.js bugs that you either reported or +1'ed to have fixed. Please review the resolved issue list and also check out the v0.5.0-rc.1 changelog.
/cc @cederberg @evanplaice @BenHall @mrchief @dark-panda @yoander @yagudaev
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?
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)
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 >
entity be unescaped? HTML strings may not always come from _.escape
; I expect this may be used with content blocks in arbitrary XML files.
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!
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.
_.template
should cache compiled function or implicite declare use cache, it will be faster.
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?
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!
_.merge({a:1}, {a:2}, {a:3}, {a:4}); // -> {a:3}
The ellipses in the documentation for merge shows that this should be possible:
_.merge(object [, source1, source2, …, indicator, stack=[]])
Edit: To get an even better idea of the problem, check out the referenced commit.
We noticed a difference in behavior between the uncompressed version of lodash and the hybrid minified one.
Basically templateSettings 'interpolate' and 'evaluate' behave differently when applied to object methods.
I created a gist here: https://gist.github.com/3132425
interpolation of obj.join() works uncompressed, compressed gives
<e%= obj.join() %>
Hi. You've been summoned because your Underscore issue has been resolved by Lo-Dash v0.4.1. Please review the resolved issue list here. If your issue is not there then it's probably related to Underscore issue #605, so please check out Lo-Dash's _.isObject method.
\cc @subimage, @dtetto, @jayphelps @khiltd, @alexandernst
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
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.
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
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
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.
As issue #23 points out, sometimes it's nice to have array methods not error when they receive a falsy value for the required array
argument.
The use case is something like
// should handle when `String#match` returns `null` without erroring
_.flatten(string.match(/regexp/))
So I would like to know if you all (/cc @kitcambridge @mathiasbynens) think it's worthwhile.
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
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?
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?
Check out this commit on my fork of lodash:
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.
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;
},
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.
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 []
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.
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
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!
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"
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?
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.
After updating to 0.4.0 I am no longer able to assign variables within templates.
e.g.
<% var listItem = list[0]; %><%= listItem.library %>
In this example listItem
is undefined when trying to access the library property.
See jsfiddles:
Using 0.3.2: http://jsfiddle.net/joshvermaire/gf84m
Using 0.4.0: http://jsfiddle.net/joshvermaire/gf84m/1
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.
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.
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
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.
Hey, what do you think of loading lodash in the documentation page so we can play with it straight from the browser console?
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.
Hi All,
You all are summoned here because I've fixed, in Lo-Dash, various Underscore.js bugs that you either reported or +1
'ed to have fixed.
If you don't see your bug fixed here, then it is fixed in the edge version of Lo-Dash:
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.