Categories
JavaScript Answers

How to Use setTimeout in JavaScript Promise Chain?

We can create a function that returns a promise that calls setTimeout so that we can use setTimeout in a promise chain.

For instance, we can write:

const delay = (t, v) => {
  return new Promise((resolve) => {
    setTimeout(() => resolve(v), t)
  });
}

(async () => {
  const one = await Promise.resolve(1)
  console.log(one)
  const two = await delay(1000, 2)
  console.log(two)
  const three = await Promise.resolve(3)
  console.log(three)
})()

to create the delay function that returns a promise by creating one with the Promise constructor.

We pass in a callback that calls setTimeout , which calls resolve with v and delays the execution of the callback by t milliseconds.

Then we use delay in an async function with other promises.

Now we should see a delay when we’re calling delay .

And 1, 2, and 3 are logged in the console log.

Categories
JavaScript Answers

How to Call document.querySelectorAll with Multiple Conditions?

We can use commas to separate different kinds of elements we want to select.

For instance, if we have the following HTML:

<form>
</form>
<p>
</p>
<legend>
</legend>

Then we can select all the elements by writing:

const list = document.querySelectorAll("form, p, legend");
console.log(list)

list would have all the elements in the HTML in the list.

Each item separated by a comma is its own CSS selector.

Categories
JavaScript Answers

How to Check If a Value Exists in an Object Using JavaScript?

We can use the Object.values method to return an array of property values of an object.

Therefore, we can use that to check if a value exists in an object.

To do this, we write:

const obj = {
  a: 'test1',
  b: 'test2'
};
if (Object.values(obj).indexOf('test1') > -1) {
  console.log('has test1');
}

We call indexOf on the array of property values that are returned by Object.values .

Since 'test1' is one of the values in obj , the console log should run.

Use the Object.keys Method

We can also use the Object.keys method to do the same check.

For instance, we can write:

const obj = {
  a: 'test1',
  b: 'test2'
};
const exists = Object.keys(obj).some((k) => {
  return obj[k] === "test1";
});
console.log(exists)

We call Object.keys to get an array of property keys in obj .

Then we call some with callback to return if obj[k] is 'test1' .

Since the value is in obj , exists should be true .

Categories
JavaScript Answers

How to Check if a JavaScript String is Entirely Made of the Same Substring?

We can use the indexOf method to return the index of the first instance of the substring in a string.

Therefore, we can use that to check if a string is repeated by checking if the index of the substring after the first instance is different from the length of the string.

To do this, we can write:

const check = (str) => {
  return (str + str).indexOf(str, 1) !== str.length;
}
console.log(check('abcabc'))
console.log(check('abc123'))

We find the index of str by starting the search from index 1 to see if it’s different from str.length .

If it is, that means str is repeated in the string once.

Therefore, the first console log is true and the second console log is false .

Use Regex Capturing Group

A more versatile way to search for repeated strings is to use regex capturing groups.

For instance, we can write:

const check = (str) => {
  return /^(.+)\1+$/.test(str)
}
console.log(check('abcabc'))
console.log(check('abcabcabc'))
console.log(check('abc123'))

to check for repeated substrings with check by checking ifstr is repeated throughout the string.

Therefore, the first 2 console logs log true and the last one logs false .

Categories
JavaScript Answers

How to Find the Size of Local Storage with JavaScript?

We can convert our browser’s local storage object into a blob to get the size of it.

To do this, we write:

const {
  size
} = new Blob(Object.values(localStorage))
console.log(size)

We call Object.values with localStorage to get an array of values of our local storage.

Then we pass that into the Blob constructor so that we can use the size property of it to get the size.

Get the Size in Kilobytes

To get the size in kilobytes, we can write our own function to calculate the number of bytes stored in local storage and convert that to kilobytes.

For example, we can write:

const localStorageSpace = () => {
  let allStrings = '';
  for (const key of Object.keys(window.localStorage)) {
    allStrings += window.localStorage\[key\];
  }
  return allStrings ? 3 + ((allStrings.length \* 16) / (8 \* 1024)) + ' KB' : 'Empty (0 KB)';
};

console.log(localStorageSpace())

We define the localStorageSpace function that concatenates all the strings together into the allStrings string.

Then we calculate the size of it by getting the length of it, multiply by 16.

And then we divide it by 8 * 1024 to convert it into kilobytes.

Finally, we add 3 to it.