Categories
JavaScript Tips

JavaScript Tips — Download Files, Performance Test, 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.

Download File Using Javascript

We can download a file with JavaScript.

To do that, we can use the Fetch API.

We can call it as follows:

fetch('https://www.w3.org/TR/PNG/iso_8859-1.txt')
  .then(resp => resp.blob())
  .then(blob => {
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = 'sample.txt';
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
  })
  .catch(() => alert('oh no!'));

We call fetch to make a GET request to the file.

Then we call blob to turn it into a binary object.

Next, we call createObjectURL to create a URL from the blob.

Then we create an a element to create an invisible link with the object URL as the URL for the a element.

Then we can call click to download the file.

Finally, we call revokeObjectURL to clean up the data URL.

Create an Object Property from a Variable Value

We can create an object from a variable by passing in the variable in between the brackets.

For instance, we can write:

obj[a] = 'foo';

Then we set the value of a as the property’s identifier.

a can be a string or a symbol.

Also, we can use the same notation in object literals.

For instance, we can write:

const obj = { [a]: b };

We pass the variable a in the brackets of the object literal.

JavaScript Hashmap Equivalent

A map is a JavaScript equivalent of a hashmap.

To use it, we create a Map instance:

const map = new Map();
map.set('foo', 'bar');
map.set('baz', 1);

We created a Map instance and call the set method to add or update entries.

Then we can use the size property to get the map’s size.

Extract a Number from a String

To extract a number from a string, we can use the match let to find all substrings that match a given pattern.

For instance, we can write:

const txt = "123 foo 456";
const nums = txt.match(/(d+)/g);

This will match all contiguous digits.

g indicates that we search in the whole string for this pattern.

d is a digit.

Then nums is [“123”, “456”] .

Check if an Array is Empty or Exists

We can check if an array is empty or exist by using the Array.isArray method and the length property.

For instance, we can write:

if (Array.isArray(array) && array.length) {
  // ...
}

We check if array is an array with Array.isArray .

Then we use the length property to get the length of the array.

We don’t have to check the length explicitly because 0 is falsy and all other numbers are truthy.

So array.length will check if the length is nonzero.

Deep Merge Objects Instead of Doing a Shallow Merge

We can deep merge objects using Lodash’s merge method.

For instance, we can write:

_.merge(obj1, obj2, obj3);

We can merge as many objects as we want with it.

The returned object won’t have properties referencing the existing objects.

Create a style Tag with Javascript

We can create a style tag with JavaScriot by using createElement to create a style element.

For instance, we can write:

const css = 'h1 { background: red; }';
const head = document.head;
const style = document.createElement('style');
style.appendChild(document.createTextNode(css));
head.appendChild(style);

We create some CSS styles in a string.

Then we get the head element with document.head .

Next, we created a style element.

And then we put the CSS in the style element.

And finally, we append the style element into the head element.

Test Performance of JavaScript Code

To test the performance of JavaScript code, we can use the console.time and console.timeEnd methods.

For instance, we can write:

console.time('test');
for(let i = 0; i < 1000000; i++){
  //...
};
console.timeEnd('test')

We call console.time with a string identifier to start the performance test timer.

Then we call console.timeEnd with the same identifier to end the timer.

Conclusion

The JavaScript console object has methods to let us measure the timing of the code.

We can download files with the Fetch API.

Map is JavaScript’s hashmap.

Lodash merge lets us deep merge objects.

We can add dynamic properties to objects.

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 *