GithubHelp home page GithubHelp logo

phuocng / 1loc Goto Github PK

View Code? Open in Web Editor NEW
6.7K 6.7K 516.0 3.27 MB

What's your favorite JavaScript single LOC (line of code)?

Home Page: https://phuoc.ng/collection/1-loc

License: MIT License

MDX 100.00%
eleventy javascript javascript-utils js-tips one-line-code one-liner tips-and-tricks

1loc's Introduction

Hey, I'm Phuoc Nguyen! ๐Ÿ‘‹

I'm a software engineer from Vietnam ๐Ÿ‡ป๐Ÿ‡ณ.

In my free time, I enjoy playing football โšฝ with my co-workers and Nintendo games ๐ŸŽฎ with my kids.

I also take care of my Border Collie ๐Ÿ•. Here's a little secret: my zodiac sign is the dog.

I hope you find useful things in this digital space ๐Ÿš€.

Collections ๐Ÿš€

Check out this list of series that cover various topics in front-end development. They're incredibly useful for both learning and your day-to-day work, just like they are for me.

Best of all, they're all free and open to contributions. If you find them helpful, please consider giving them a GitHub star ๐Ÿ˜. Your support is greatly appreciated!

My top JavaScript utilities, in just One Line of Code!

Common ways to solve cross-browser compatibility problems

Awesome CSS animations: examples of stunning animations without external libraries

A collection of popular CSS layouts and patterns that you can use right away

Front-End development mastery: simple tips, tricks, and best practices

Mastering DOM manipulation with vanilla JavaScript

Understanding the difference between หหห and หหห in front-end development

In-depth series ๐Ÿงช

Are you a front-end engineer looking to take your skills to the next level? Then you're in luck! I'm excited to present to you our in-depth series covering advanced techniques and patterns in front-end development.

Our series is designed to provide you with real-life examples that you can use for your applications. We understand that learning can be a daunting task, which is why we've curated our content to be both engaging and informative. You won't find any boring material here!

In this series, we'll cover a range of topics, including advanced CSS, JavaScript, as well as popular front-end libraries. Our goal is to help you become a more well-rounded and skilled front-end developer.

It's important to follow the posts in the correct order, starting from the first one and working your way to the last. There are some important techniques introduced in between that you won't want to miss.

Enhancing user experience through text area mirroring

Your complete guide to mastering the use of "ref" in React

Master the art of drag and drop in React

Questions? ๐Ÿ™‹

Do you have any questions about front-end development that you'd like to learn more about? Shoot me a message on Twitter or assign me a new issue.

I've got a long list of upcoming posts, but I want to make sure I'm covering the topics that you're most interested in. Let's learn together! Sharing knowledge is the best way to grow in this field ๐Ÿฅท.

Contact

1loc's People

Contributors

anuraghazra avatar chety avatar codepo8 avatar dependabot[bot] avatar elkarouani avatar glennfaison avatar iamandrewluca avatar ietienam avatar inoyakaigor avatar islamozbek avatar jjswifty avatar jnields avatar johandalabacka avatar jonrandy avatar kwaimind avatar marcobiedermann avatar mattjared avatar munizart avatar n-iwata avatar namysh avatar nath1as avatar onelifemedia avatar philippefutureboy avatar phuocng avatar piyushsuthar avatar provenr avatar robinpokorny avatar sporium avatar tugsanunlu avatar vreymond 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

1loc's Issues

getIntersection doesn't work for arrays with repeated values

Since your check for an element being in the intersection is for it's count in the flattened array of arrays to be equal to the number of total arrays, this doesn't work correctly if one of the arrays has repeated values.

e.g. getIntersection([ 1, 1 ], [ 2, 3 ]) returns [ 1 ]

[FEATURE] Pluralise based on length of array.

A simple line of code to pluralise a word based on the length of an array.

const pluralise = (items, singular, plural) => items.length > 1 || items.length === 0 ? plural : singular;

Use Case

For if you have copy text that requires the interchangeability of pluralising based on the amount of items in an array.

let items = [0];
let string = `The ${pluralise(items, "test", "tests")}.`
console.log(string); // 'The item.'
items = [0, 1, 2, 3];
console.log(string); // 'The items'

"npm i" failed

D:\Playground\JS\1loc>node -v
v16.17.0

D:\Playground\JS\1loc>npm i
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: 1loc@undefined
npm ERR! Found: [email protected]
npm ERR! node_modules/next
npm ERR!   next@"^11.1.2" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer next@"^12.0.0" from @1milligram/[email protected]
npm ERR! node_modules/@1milligram/design
npm ERR!   dev @1milligram/design@"^0.4.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\pc\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\pc\AppData\Local\npm-cache\_logs\2022-08-27T06_18_59_963Z-debug-0.log

Checking for an empty array can be faster

I made a simple performance test and it shows that getting length of array keys is not optimal code. I propose change it to a.filter(Boolean).length > 0. This code can be faster from 4.5 (Firefox) or 5.9 (Chrome) to 26 (Safari) times.

image

[FEAT] Add a search bar to find snippets

Add a search bar to the header section of the website 1loc.dev. So users can search the snippets they need. I don't know how to do it. The snippets are in MD files. Does anyone know how to add the search functionality to it?

"Check if an array is empty" is incorrect

There is a problem with checking that the array is empty. When the parameter is "", the result is true.
"const isEmpty = arr => !Array.isArray(arr) || arr.length === 0" error
"const isEmpty = arr => Array.isArray(arr) && arr.length === 0" right

fool questions

This is the first time I submit code in someone else's warehouse. May I pull your code to my computer, and then after I modify it, can I create a new branch for submission? Or how should I put the modified version? Code to you.

isEqual is buggy

Hi,

You should alert that

const isEqual1 = (a, b) => JSON.stringify(a) === JSON.stringify(b)

isn't similar to

const isEqual2 = (a, b) => a.length === b.length && a.every((v, i) => v === b[i])

and both are valuable (and similar) only if all array elements are boolean|finite number|string

// buggy if NaN
isEqual1([NaN], [NaN]) // => true
isEqual2([NaN], [NaN]) // => false

// buggy if object
// plain object
isEqual1([{a: 42}], [{a: 42}]) // => true
isEqual2([{a: 42}], [{a: 42}]) // => false
// array
isEqual1([[42]], [[42]]) // => true
isEqual2([[42]], [[42]]) // => false
// Date
isEqual1([new Date('2021-03-30')], [new Date('2021-03-30')]) // => true
isEqual2([new Date('2021-03-30')], [new Date('2021-03-30')]) // => false

And the json comparaison can be dangerous

isEqual1([NaN], [null]) // => true
isEqual1([Number.POSITIVE_INFINITY], [Number.NEGATIVE_INFINITY]) // => true
isEqual1([Number.POSITIVE_INFINITY], [null]) // => true

The only correct way to compare would be to test type of each element then value, in a recurse manner, but it needs a very long line of code ;-) (eg lodash implementation

You can limit to the area where the code is valid with something like

// returns undefined when we can't decide in a such easy way
const isEqual = (a, b) => a.every((v, i) => (['boolean', 'string'].includes(typeof v) || (typeof v === 'number' && !Number.isNaN(v)))) ? a.length === b.length && a.every((v, i) => v === b[i]) : undefined

// or throw (which seems better in real life, because undefined is falsy and previous function can leads to bugs hard to detect)
const isEqual = (a, b) => a.length === b.length && a.every((v, i) => { if (['boolean', 'string'].includes(typeof v) || (typeof v === 'number' && !Number.isNaN(v))) return v === b[i]; throw Error('isEqual can only compare array of boolean|string|number') })

Not working on window machine

When I tried to run npm run dev-server I get this error:

D:\Desktop\1loc>npm run dev-server

> 1loc@ dev-server D:\Desktop\1loc
> npm run copy && npm run data && webpack-dev-server


> 1loc@ copy D:\Desktop\1loc
> rm -rf dist && mkdir dist && cp -rf public/* dist

'rm' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! 1loc@ copy: `rm -rf dist && mkdir dist && cp -rf public/* dist`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the 1loc@ copy script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!   \2020-07-28T14_20_19_677Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! 1loc@ dev-server: `npm run copy && npm run data && webpack-dev-server`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the 1loc@ dev-server script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!    -debug.log

is it the rm -rf command is not for window?

[CHORE] Add issue and pull request templates

People tend to provide feedback as words come into their head; templates are always a great way of helping people to structure what they need to write, and help you to ask them what you are interested in.

GitHub allows you to create templates for Issues and Pull Requests.

Also, check out this awesome-github-templates GitHub repository that contains info about how to create templates, as well as a couple of examples.

Note: The templates can be changed according to this project

My suggestions for issue & PR templates

No style after startup

npm run watch:eleventy & npm run watch:sass , change into ๏ผŒnpm run watch:eleventy | npm run watch:sass ใ€‚

Compare two arrays regardless of order has siteeffects

Hi there,

your Sippet for comparing Arrays has an important downside. It sorts the original arrays, which is not the espected behaviour.
I suggest to fix it by cloning the arguments before sorting it or using Sets if number of sam items does not matter.

The current snippet:
// a and b are arrays
const isEqual = (a, b) => JSON.stringify(a.sort()) === JSON.stringify(b.sort());

// Examples
isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [1, 3, 2]); // true
isEqual([1, 2, 3], [1, '2', 3]); // false

Empty an array snippet

image

Really? If you want, I can create snippet for "empty any variable", see: "var = null", is it OK for you?

I can also create some snippets like "set variable to one", its easy: "a = 1;", are you need for snippets for create variables from one to ten? Its easy too:
a = 1;
a = 2;
a = 3;
a = 4;
a = 5;
a = 6;
a = 7;
a = 8;
a = 9;
a = 10;

Please, add my snippets to your stupid list.

Convert letter to emoji

'a' to '๐Ÿ‡ฆ', 'b' to '๐Ÿ‡ง', etc.

c => String.fromCodePoint(c.toLowerCase().charCodeAt() + 127365);

Mobile view not responsive

Looking at this on iOS 15.2 Safari on an iPhone 11 Pro, it doesn't render correctly at all.

Screenshot:
image

Compare two arrays regardless of order is simply incorrect

https://github.com/1milligram/1loc/blob/cecbfa239c1d6c9d527518c157b9ea20c4140c9b/snippets/array/compare-two-arrays-regardless-of-order.md?plain=1#L10

The Set object lets you store unique values of any type, whether primitive values or object references.

And an array can have duplicate values.

So it fails simplest of tests: isEqual([1], [1, 1]);
Checking for length would be incorrect too, consider such case: isEqual([1, 1, 2], [1, 2, 2]);

Also concerns from #414.

And lastly one should keep in mind that:

const a = {a: 1};
const b = {...a};
a !== b; // true

Maybe it should be documented on equality function page.

About Contribution

I'm sorry, I'm sorry, I'm not very good at GitHub and I seem to be making a mess of commits.

wrap() is wrong

#489

import { describe, it, expect } from "@jest/globals";
import { wrap } from "./num";

describe("wrap", () => {
  it("works", () => {
    expect(wrap(11, 10, 25)).toEqual(11);
    expect(wrap(10, 10, 25)).toEqual(10);
    expect(wrap(9, 10, 25)).toEqual(25);
    expect(wrap(24, 10, 25)).toEqual(24);
    expect(wrap(25, 10, 25)).toEqual(25);
    expect(wrap(26, 10, 25)).toEqual(10);
  });
});

If you actually run these test you get different values from what is expected.

Local development error.

i was trying to run npm run dev-server but it throws this error, i thinks its trying to find some /data/data.json folder

View logs
$ npm run dev-server

> 1loc@ dev-server D:\CAM Files\Dreamwaver\Javascript\contrib\1loc
> npm run copy && npm run data && webpack-dev-server


> 1loc@ copy D:\CAM Files\Dreamwaver\Javascript\contrib\1loc
> rm -rf dist && mkdir dist && cp -rf public/* dist


> 1loc@ data D:\CAM Files\Dreamwaver\Javascript\contrib\1loc
> node bin/generateData.js

internal/fs/utils.js:230
    throw err;
    ^

Error: ENOENT: no such file or directory, open 'D:\CAM Files\Dreamwaver\Javascript\contrib\1loc\data\data.json'
    at Object.openSync (fs.js:457:3)
    at Object.writeFileSync (fs.js:1282:35)
    at Object.<anonymous> (D:\CAM Files\Dreamwaver\Javascript\contrib\1loc\bin\generateData.js:32:4)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
    at internal/main/run_main_module.js:18:47 {
  errno: -4058,
  syscall: 'open',
  code: 'ENOENT',
  path: 'D:\\CAM Files\\Dreamwaver\\Javascript\\contrib\\1loc\\data\\data.json'
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! 1loc@ data: `node bin/generateData.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the 1loc@ data script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\user\AppData\Roaming\npm-cache\_logs\2020-05-04T16_35_33_909Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! 1loc@ dev-server: `npm run copy && npm run data && webpack-dev-server`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the 1loc@ dev-server script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\user\AppData\Roaming\npm-cache\_logs\2020-05-04T16_35_33_953Z-debug.log

Compare two arrays regardless of order

This code doesn't work in some cases:
// Or
const isEqual = (a, b) => a.length === b.length && a.every((v) => b.includes(v));

For example:
isEqual(['a', 'a'], ['b', 'a'])
gives true, but it must be false.

Add disclaimer to isPowerOfTwo

Saw this repo b/c it was in js weekly newsletter. B/c of the way bitwise AND work on numbers in JS (casting down to 32-bit signed integers), the isPowerOfTwo function will return a lot of false positives:

// Any non-integer `< 2 ** 32` will be floored.
// Below, the bitwise operation turns 1.5 into 1.
isPowerOfTwo(1.5); // true

// Only the least-significant 32 bits are saved in bitwise ops.
// Below, the bitwise operation turns number into 1.
isPowerOfTwo(2 ** 40 + 1); // true

though afaik it should work with it's BigInt variant:

const isPowerOfTwo = number => (number & (number - 1n)) === 0n;

isPowerOfTwo(2n ** 40n + 1n); // false 

Maybe add a disclaimer to the function specifying that it only works on positive integers <= 2 ** 32?

Add TypeScript variants?

Are you planning to add TypeScript variants with the possibility to switch between both on the website? I'm willing to help adding the types. (...wait, I just realized the site is written in TypeScript ๐Ÿ˜ƒ)

JSON.stringify a Object with circular references

even though not a simple single liner, we is a lot of Object/Array comparisons in the provided examples which use the Stringify function, but the default replacer isn't circular reference safe.

the example I made in screenshot is circular reference safe, ( will skip over circular references ).

might be good to include it, but maybe not if we are thinking all of the examples must be single liners.

maybe its just worth mentioning in the single line examples as a comment that isn't circular reference safe, and link to a separe document (that isn't one liners) on how to handle those if they need to.

image

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.