1

7 JavaScript One-Liners to Save Your Day

 2 years ago
source link: https://blog.bitsrc.io/5-javascript-one-liners-to-save-your-day-82a065d05017
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

7 JavaScript One-Liners to Save Your Day

Do this instead of writing your own functions

In this blog, we are going to cover some JavaScript one-liners that might save your day.

1. Shuffle the array and return an array

You can shuffle the array using the random method of the math module.

const shuffle = array => array.sort(() => 0.5-Math.random());//outputshuffle([1,5,2,45])  [5,2,1,25]

Math.random() returns a random number between 0 and 1. So if it happens to give you a number less than 0.5 then you get a negative number and if it’s over that then you get a positive.

The reason 0.5 is chosen in this compare function is that if you subtract 0.5 from each of the endpoints of 0 and 1, you get a new range of -0.5 and +0.5, but +0.5 is not included because the original 1 is not included in the result of the Math.random() function.

So when a random number is returned from this range, there is an almost equal chance it will be either positive or negative, and sometimes it will also be zero.

2. Generate a random string

Sometimes there may be a situation where you need to generate random strings, use this snippet of code to obtain that.

const randomstr = Math.random().toString(36).substring(7)

It will generate anywhere between 0 and 6 characters due to the fact that trailing zeros get removed when stringifying floating points.

3. Detecting dark mode

There may be situations where you want to do some extra things when dark mode is activated, use this snippet of code to check whether the dark mode is on or off.

const isDark = window.matchMedia && window.matchMedia(`(prefers-color-scheme:dark)`).match

4. Remove duplicates from an array

Removing duplicate elements is one of the common things that we do in an array, use this one-liner to achieve this.

const num = [1,2,2,2,5,66,666,55,5]
const name = ["adarsh","gupta","adarsh","raj","ratesh","raj"]const uniquenum = [... new Set(num)]
// [1,2,5,66,666,55]const uniquenames = [... new Set(name)
// ["adarsh","gupta","raj","ratesh"]

5. Reverse a string

Reverse a string has never been such easy, firstly we convert it into an array (an array of characters), now we reverse that array then we convert that array into a string.

Use this one-liner to achieve this:

const rev = (str) => str.split("").reverse().join("")

6. Check if an array is not empty

Checking if an array is empty or not using the isArray method and confirming it by checking the length of Object.keys(arr) by passing the array.

The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.

const isArrayNotEmpty = (arr) => Array.isArray(arr) && Object.keys(arr).length > 0; // ExamplesisArrayNotEmpty([]); // falseisArrayNotEmpty([1, 2, 3]); // true

7. Swapping two variables

The below code is one of the simpler ways to swap two variables without using a third variable and with just one line of code.

[var1, var2] = [var2, var1];

Conclusion

We have learned 5 awesome JavaScript one-liners on this blog. I hope you have found these useful. Be sure to follow me on Twitter as I'm active on there too.

Build composable web applications

Don’t build web monoliths. Use Bit to create and compose decoupled software components — in your favourite frameworks like React or Node. Build scalable and modular applications with a powerful and enjoyable dev experience.

Bring your team to Bit Cloud to host and collaborate on components together, and speed up, scale, and standardize development as a team. Try composable frontends with a Design System or Micro Frontends, or explore the composable backend with serverside components.

Give it a try →

Learn more


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK