Git Product home page Git Product logo

you-dont-need-lodash-underscore's Issues

Opera browser support is misleading

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:

opera

_.omit for collections

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' }

What are the checkmarks for?

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!

Disallow aliases

_ 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);

You DO need Lodash

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.

Equivalent of _.minBy and _.maxBy

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, {});
};

Definitions not found for multiple methods

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

very useful lodash functions that are NOT in es6, es7, es8

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:

  1. _.has()
    let test1 = {
    a: {
    b:{
    c: {
    d: 56
    }
    }
    }
    }
    // es6:
    if(test1 && test1.a && test1.a.b && test1.a.b.c && test1.a.b.c.d){console.log('foo')}
    // lodash:
    _.has(test1, 'a.b.c.d')
  2. _.chunk()
  3. _.isPlainObject()
  4. _.flatten()
  5. _.groupBy()

There are many others, I just listed the ones I used.

Should error / warn when using import or require

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?

lodash _.times

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]

Performance

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

Null safety

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?

_.isArray

Hi! Nice plugin! What about _.isArray rule which could be natively replaced by Array.isArray?

`_.groupBy` equivalent

// 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] }

fix(uniq): incompatible with Internet Explorer

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:
screen shot 2018-11-30 at 11 30 03 am

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).

Cannot find module 'eslint-config-you-dont-need-lodash-underscore:compatible-error'

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

Proposition for _.set equivalent

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?

lodash fp

I don't think the linter should error/warn if user is importing lodash fp. Thoughts?

Default ESLint configs

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:

  • you-dont-need-lodash-underscore:all (all rules set to warn)
  • you-dont-need-lodash-underscore:all-strict (all rules set to error)
  • you-dont-need-lodash-underscore:safe (rules in which the native implementation exactly matches the _ one are set to warn)
  • you-dont-need-lodash-underscore:safe-strict (rules in which the native implementation exactly matches the _ one are set to error, the rest are set to warn)

What do you think? I'll go ahead and get a pull request started.

Collection iteration on objects works as well

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

missing _.partial and _.after in the rules

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.

Shimering all not-yet-available functions natively

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?

Add a CHANGELOG

Thanks for this project! Would it be possible to add a CHANGELOG? This helps users keep track of new versions and features.

Is not iterable error with native impementation of _.flatten

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"]

Show complex use-cases

  _.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;
  });

_.each for Collections

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)

trimStart and trimEnd

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.

Use optional chaining operator instead of _.get

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').

Enforce a consistent code style

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.

reduceRight native example is wrong

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".

Equivalent of _.without

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?

Roadmap

Is there a roadmap for this project to display which functions to implement?

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.