you-dont-need / you-dont-need-lodash-underscore Goto Github PK
View Code? Open in Web Editor NEWList of JavaScript methods which you can use natively + ESLint Plugin
License: MIT License
List of JavaScript methods which you can use natively + ESLint Plugin
License: MIT License
First, I'd like to thank you for creating this repository. It is great to read about native possibilities of browser. Unfortunately, I found "browser support" comparison very misleading, because ou noted that some of _.*
functions are "Not supported" but it is not truth since Opera uses blink/chromium. When I saw it then I thought that you have taken into consideration only Opera based on Presto engine, but browser support for _.assign
function mentions that Opera v32 is compatible (v32 is not Presto-based).
Opera 38:
Doesn't match behaviour exactly IIRC, but matches close enough for most people's use cases
support you-dont-need-lodash-underscore rule documentation links for plugins
when I click the anchor link I get landed here: https://github.com/jfmengels/eslint-rule-documentation/blob/master/contributing.md
screenshot taken using atom eslint plugin. https://atom.io/packages/linter-eslint
Omitting can easily be done this way:
const object = { a: 1, b: '2', c: 3 };
const omit = (obj, arr) =>
Object.entries(obj).reduce((acc, cur) => {
if (!arr.includes(cur[0])) {
acc[cur[0]] = cur[1];
}
return acc;
}, {});
omit(object, ['a', 'c']); // => { 'b': '2' }
Maybe this is a dumb question, but next to the browser version numbers, there are sometimes checkmarks, sometimes not. Fore example:
https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#browser-support-2
Why does the Firefox version have a checkmark, but not Chrome or Safari? I couldn't find anything in the page to explain this. Although I did mostly just skim, so my bad if I missed it. Maybe add an explanation for that, if it is indeed indicating something specific about browser support.
BTW great little reference, thanks!
_ libraries sometimes provide the exact same function under multiple names, e.g. each/forEach.
The ESLint plugin should have options to require the use of one particular alias over the others.
/*eslint you-dont-need-lodash-underscore/forEach: ["error", { preferNative: "never", alias: "forEach" }]*/
// invalid
_.each([1,2,3], fn);
// valid
_.forEach([1,2,3], fn);
As @stevemao and others have brought to my attention, there are cases where Lodash provides advantages over the native library. They can provide more consistency across implementations, better performance in typical real world use, or both.
Therefore I think the ESLint plugin should provide options to encourage changing native functions to _ equivalents. Similar to how the no-semi rule provides options to either require semicolons or disallow them.
A very simple workaround is
var array = [1, 2, 3];
array.indexOf(1) !== -1;
// → true
Can I add examples to this project?
min-by.js
export default (collection, key) => {
return collection.reduce((a, b) => a[key] <= b[key] ? a : b, {});
};
max-by.js
export default (collection, key) => {
return collection.reduce((a, b) => a[key] >= b[key] ? a : b, {});
};
I'm getting errors including what looks to be valid rules. Errors are occurring for these rules: findIndex, indexOf, lastIndexOf, forEach, reduceRight, after, isNaN, extendOwn, toLower, toUpper
warning Definition for rule 'you-dont-need-lodash-underscore/indexOf' was not found you-dont-need-lodash-underscore/indexOf
I am totally agree using native functions like filter, map, reduce, findIndex, etc over the lodash ones, but I found useful some lodash functions like:
There are many others, I just listed the ones I used.
These days there are lots of ways to pull in a lodash function. I would expect each of these to generate errors.
import forEach from 'lodash/forEach'
import whatever from 'lodash/forEach'
import { forEach } from 'lodash'
import { forEach as whatever } from 'lodash'
import forEach from 'lodash.foreach'
import whatever from 'lodash.foreach'
const forEach = require('lodash/forEach')
const whatever = require('lodash/forEach')
const { forEach } = require('lodash')
const { forEach: whatever } = require('lodash')
const forEach = require('lodash.foreach')
const whatever = require('lodash.foreach')
I was surprised that this wasn't generating errors in my project. Did I miss something?
missing _.extend in the rules
What about _.times function. There is es6 Array.from, which lets somewhat replicate that function.
let out = Array.from(Array(10), (_,x) => x);
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Hello,
Just a quick comment that @jdalton (Microsoft) has investigated the performance implications of using native over abstraction libraries and it appears native is generally slower.
I think it would be worth making note of this within your README as it's otherwise a bit misleading.
Thanks
Lodash's isNil(value)
is equivalent to value == null
. That's even how it's implemented.
Wouldn't this be noteworthy to mention in this repo as well?
Update: The same applies to isNull(value)
, which is equivalent to value === null
.
First of all thanks so much for this library, love using this plugin to remove old lodash uses.
I wanted to quickly broach the topic of null safety; many functions in lodash, e.g. _.keys, _.entries are null safe. The same safety can be achieved by using the native methods like so: Object.keys(value || {})
As this could be breaking for those of us converting, it would be great if this were mentioned in the error messages and the readme. I'm happy to do a PR with a draft of these changes, but as this is an issue that effects a number of functions I figured you might want some input over how to change the text.
I propose something like "Object.keys(value || {})"
in rules.json, and maybe Consider using the native Object.keys as Object.keys(value || {})
in the error messages?
Hi! Nice plugin! What about _.isArray
rule which could be natively replaced by Array.isArray
?
Hi Guys, first of all, thank you all for your support for this project.
I'd like to have a polls to find out if you guys like this list to include some native implementations which are not built-in functions. For example _.after
The poll link is here: Polls link
Your suggestions are important.
// Underscore/Lodash:
_.groupBy(['one', 'two', 'three'], 'length');
// => { '3': ['one', 'two'], '5': ['three'] }
// Native
['one', 'two', 'three'].reduce((result, value) => {let key = String(value.length); result.hasOwnProperty(key) ? result[key].push(value) : (result[key] = [value]); return result}, {})
// => { '3': ['one', 'two'], '5': ['three'] }
// Native (shorter version):
['one', 'two', 'three'].reduce((result, value, i, a, key = String(value.length)) => ((result[key] = result[key] || []).push(value), result), {})
// => { '3': ['one', 'two'], '5': ['three'] }
An other example:
// Underscore/Lodash:
_.groupBy([6.1, 4.2, 6.3], Math.floor);
// => { '4': [4.2], '6': [6.1, 6.3] }
// Native
[6.1, 4.2, 6.3].reduce((result, value) => {let key = String(Math.floor(value)); result.hasOwnProperty(key) ? result[key].push(value) : (result[key] = [value]); return result}, {})
// => { '4': [4.2], '6': [6.1, 6.3] }
Hi
Firstly- great repo.
I've found an issue with _.uniq
and Internet Explorer (IE). In your docs, it says your example supports IE. It does not., it IE does not support new Set(iterable)
See screenshot from mdn
below:
So, in the example for uniq
we could change:
[...new Set(array)];
to...
array.filter((v, i, a) => a.indexOf(v) === i)
I'm happy to create a PR for this (but don't have access to this repo).
I'm not sure what I'm doing wrong. I installed eslint-plugin-you-dont-need-lodash-underscore
via NPM but ESLint can't find any of the configs.
Note that ESLint can find the plugin - when I enable a rule like "you-dont-need-lodash-underscore/for-each": "error",
eslint runs successfully.
% node_modules/.bin/eslint src
Cannot find module 'eslint-config-you-dont-need-lodash-underscore:compatible-error'
Referenced from: /Users/keithlea/Code/thrift2flow/.eslintrc
Error: Cannot find module 'eslint-config-you-dont-need-lodash-underscore:compatible-error'
Referenced from: /Users/keithlea/Code/thrift2flow/.eslintrc
at ModuleResolver.resolve (/Users/keithlea/Code/thrift2flow/node_modules/eslint/lib/util/module-resolver.js:74:19)
at resolve (/Users/keithlea/Code/thrift2flow/node_modules/eslint/lib/config/config-file.js:515:25)
at load (/Users/keithlea/Code/thrift2flow/node_modules/eslint/lib/config/config-file.js:532:26)
at configExtends.reduceRight.e (/Users/keithlea/Code/thrift2flow/node_modules/eslint/lib/config/config-file.js:424:36)
at Array.reduceRight (native)
at applyExtends (/Users/keithlea/Code/thrift2flow/node_modules/eslint/lib/config/config-file.js:408:28)
at Object.load (/Users/keithlea/Code/thrift2flow/node_modules/eslint/lib/config/config-file.js:566:22)
at loadConfig (/Users/keithlea/Code/thrift2flow/node_modules/eslint/lib/config.js:63:33)
at getLocalConfig (/Users/keithlea/Code/thrift2flow/node_modules/eslint/lib/config.js:130:29)
at Config.getConfig (/Users/keithlea/Code/thrift2flow/node_modules/eslint/lib/config.js:260:26)
[keithlea:~/Code/thrift2flow] master(+3/-2,+1/-1)* 2d23h56m11s 1 ± npm ls eslint
[email protected] /Users/keithlea/Code/thrift2flow
└── [email protected]
% npm ls eslint-plugin-you-dont-need-lodash-underscore
[email protected] /Users/keithlea/Code/thrift2flow
└── [email protected]
% npm -v
4.0.5
% node -v
v6.10.0
_.padEnd
/ _.padStart
has corresponding ES6 methods.
Hi,
Thank you for this repo, it gaves me lot of ideas to refactor my code.
I would like to suggest a replacement for the _.partial
method, using Rest and Spread operators of ES6:
Create a function that calls func with args.
// Lodash
function greet(greeting, name) {
return greeting + ' ' + name;
}
var sayHelloTo = _.partial(greet, 'hello');
// Native
function greet(greeting, name) {
return greeting + ' ' + name;
}
var sayHelloTo = (...args) => greet('hello', ...args)
What do you think of it? Is there any flaw?
I don't think the linter should error/warn if user is importing lodash fp. Thoughts?
Now that individual ESLint rules have been broken out (+1, very nice work Steve!) we should add some default configs so that folks don't have to configure each individual rule.
I'm thinking we can provide a few options:
What do you think? I'll go ahead and get a pull request started.
const sample = { 'a': 1, 'b': 2 };
_.each(sample, function(value, key) {
console.log(key, value);
});
Object.entries(sample).forEach(([key, value]) => {
console.log(key, value);
})
// => Logs 'a' then 'b' (iteration order is not guaranteed).
Although the browser support may vary, and some people don't like the verboseness. Is this something worth mentioned? I'm happy to make PR
Anyone got idea why quick link is not working? Need markdown expert 👍
The alternative
message could be "an arrow function". We'd have to change the default prefix from "Consider using the native " to "Consider using ". While we're at it, we might as well change the prefix to "Use " to keep the message short.
Glad to find out about this project. I was actually thinking of doing something similar lately.
For a while, people installed LoDash to have access to functions like _.map()
, _.reduce()
etc.
I have never been sure about this, but I think those library did not modify the Array
object inner methods through Array.prototype.map = function() {}
to avoid conflicts with the possibly existing native method. Am I correct?
Well, I think the time has now come to actually do this.
Imagine a lib, that would look at the existing native methods in the current JS engine, and extend its JS capacities with all the non-existing ones.
The point would be to actually increase JS capacities so that devs start using them, and then letting some time to the ECMA community to integrate those methods natively. This would also prevent some risible fails like the NPM LeftPad Package issue.
Would it make sense as project? Are there any pros/cons in doing this?
It would start with something like:
Array.prototype.map = Array.prototype.map || function(iteratee) {
// LoDash Code
var index = -1,
result = Array(this.length);
while (++index < this.length) {
result[index] = iteratee(this[index], index, this);
}
return result;
}
Array.prototype.sum = Array.prototype.sum || function() {
this.reduce(function(sum, el, i) {
if (el.isNumber())
return el + sum;
return sum;
}, 0);
}
JS is just about to be a great language, why not living in the future already?
I couldn't find any .fill
method on array on the MDN
Thanks for this project! Would it be possible to add a CHANGELOG
? This helps users keep track of new versions and features.
Tested on Google Chrome 61.
[1, [2]].reduce((a, b) => [ ...a, ...b ], [])
returns error:
Uncaught TypeError: b is not iterable
at reduce (<anonymous>:1:32)
at Array.reduce (<anonymous>)
at <anonymous>:1:5
But if I pass string instead of number, works fine:
['2', ['3']].reduce((a, b) => [...a, ...b], []);
>> ["2", "3"]
_.each([1, 2, 3], function(value, index) {
console.log(value);
});
is simple use-case only
what about
_.each([1, 2, 3], function(value, index) {
...
return false;
});
Can be achieved with Object.entries
and arr.forEach
const collection = {foo: 'a', bar: 'b', baz: 'c'};
Object.entries(collection).forEach(([key, value], index) => {
console.log(key, value, index);
});
// => "foo" "a" 0
// => "bar" "b" 1
// => "baz" "c" 2
This pattern also works on Array (though I don't know why you'd use it over a regular .forEach
for that)
There is no entry for [_.cloneDeep(value)
] (https://lodash.com/docs/4.17.5#cloneDeep). I am not really sure whether this makes any sense. But here it is suggested that the following expression can clone (at least) objects.
JSON.parse( JSON.stringify( obj ) );
For further information see this StackOverflow question.
Should this be adapted into the list?
I think .trimStart
and .trimEnd
are easily replaceable:
_.trimStart(str) === str.replace(/^\s+/, '')
_.trimEnd(str) === str.replace(/\s+$/, '')
Just wanted to make sure it's ok and that I'm not missing anything here, so I can add a PR to add this to the README.
Update: I realize that these two lodash functions have an extra argument with the chars to be replaced. I still think it's doable, but perhaps it over complicates things. Perhaps we could mention in the README that when not needing to pass the second argument, it's possible to simply use the alternatives I list below, and leave the usage of the lodash functions for when the second argument is needed.
need to extend _.uniq
alternative examples to include uniq'ing by an attribute.
example:
_.uniq([{a: 1}, {a: 2}, {a: 1, b: 1}])
// versus
_.uniq([{a: 1}, {a: 2}, {a: 1, b: 1}], o => o.a)
https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_uniq
Hi!
I have a feature request. It would be cool to have you-dont-need-lodash-underscore/prefer-optional-chaining-operator
rule, which enforces using foo?.bar?.buz
instead of _.get(foo, 'bar.buz')
.
to add to the _.flatten
example, there is a native flat
.
supplemental:
Microsoft is killing IE and Chakra is getting a lot of attention now :)
I found some inconsistencies in the code style, especially the space around infix operators.
return element >=10;
return value*2;
return value >= 10;
I think that it will be better to enforce a consistent style in this project, such as JavaScript Standard Style or anything else.
inner peace....
Maybe add version support for browsers with polyfill (https://github.com/es-shims/es5-shim)?
var array = [0, 1, 2, 3, 4];
var result = array.reduce(function (previousValue, currentValue, currentIndex, array) {
return previousValue - currentValue;
});
console.log(result);
// output: -2
The above output is not "-2" it is "-10".
_.bind
has been replaced with Function#bind
and arrow functions (when using .this
)
Edit: arrow functions do not support new
, so they aren't a complete replacement.
Hi,
Is there an elegant way to remove an item from an array in an immutable way without using underscore?
I want _.without([1,2,3],2)
to return [1,3]
.
The original array should remain unmodified.
I'd like to avoid using a syntax involving indexes, slice, splice or whatever because I never remember it and using _ is much simpler.
Is there any simple way with ES next?
missing _.assign in the rules
Is there a roadmap for this project to display which functions to implement?
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.