Categories
JavaScript Tips

JavaScript Tips — Date Difference, Sleep, and More

Spread the love

Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.

In this article, we’ll look at some solutions to common JavaScript problems.

Pause a Node Program for a Period of Time

We can pause a Node program for a period of time with the setTuimeout method.

For instance, we can write:

setTimeout(() => console.log('pause'), 3000);

We can also create a promise with the setTimeout function in it.

For instance, we can write:

const sleep = (ms) => {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

We created a sleep function to return a promise.

resolve is called when the timeout is over.

ms is the timeout duration in milliseconds.

Then we can use it by writing:

const run = async () {
  console.log('foo');
  await sleep(1000);
  console.log('bar');
}

We call sleep to pause the run function between the 2 console logs.

Update Nested State Properties in React

We can updated nested state properties by using the spread operator.

For instance, we can write:

this.setState({ foo: { ...this.state.foo, flag: false } });

Then we set the foo state with the new value of flag while retaining the rest of the this.state.foo object.

setState is used in class components.

If we use hooks, we can write:

setFoo({ ...foo, flag: false });

where setFoo is the state change function returned by useState .

How to Get a Key in a JavaScript Object by its Value

We can get a key in a JavaScript object by its value by inverting the keys and values.

Then we can get the value by the key of the inverted object.

To do that, we can use Underscore’s invert method.

For instance, we can write:

const obj = {
  foo: 3,
  bar: 4
};

(_.invert(obj))[3];

We flipped the obj keys an values and return the new object with invert .

Then we can get the key by the value of the original object.

The same method is available with Lodash.

Passing Arguments Forward to Another JavaScript Function

To pass an arguments forward to another function, we can use the apply method.

For instance, we can write:

const a = (...args) => {
  b.apply(null, args);
}

const b = (...args) => {
  console.log(args);
}

Then we can call a :

a(1, 2, 3);​

We call the a function with the arguments we want to pass in.

Then we use apply to call b with the same arguments.

args is an array of arguments that are passed in.

Likewise, we can use the spread operator to spread the arguments instead of using apply :

const a = (...args) => {
  b(...args);
}

const b = (...args) => {
  console.log(args);
}

Moment.js Date-Time Comparison

We can compare date and time by using the diff method.

For instance, we can write:

moment().diff(dateTime, 'minutes')

moment() and dateTime are both moment objects.

We call diff on moment() to compare that with dateTime and get the difference in minutes by passing in 'minutes' .

moment() gets the current date-time as a moment object.

Alias a Default import in Javascript

To alias a default import in JavaScript, we can just name it whatever we want.

For instance, we can write:

import alias from './module';

to import the module ‘s default import with the name alias .

Or we can write:

import { default as alias } from './module';

to do the same thing.

Convert Array to JSON

To convert an array to JSON, we can call JSON.stringify on the array.

For instance, we can write:

const str = JSON.stringify(arr);

where arr is the array.

Get Distinct Values from an Array of Objects

To get distinct values from an array of objects, we can use the map method and put the items into a set to remove the duplicates.

For instance, we can write:

const distincts = [...`new Set(arr.map((item) => item.id))]`

We call the map method on arr to get all the id property values into an array.

Then we use the Set constructor to create a set from the array of id values to remove the duplicates.

Finally, we convert the set back to an array with the spread operator.

Conclusion

We can pause a program by using promises.

Sets are useful for removing duplicates.

We can use the rest operator to get all the arguments of an object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *