Categories
JavaScript Answers

How to Implement a Stack and a Queue in JavaScript?

Stacks and queues are basic data structures that we may use in our JavaScript programs.

Stacks let us add items to it and the last item that’s added is the first item that can be removed.

Queues let us add items to it and the first item that’s added is the first item that can be removed.

In this article, we’ll look at how to implement a stack and a queue with JavaScript.

JavaScript Stack Methods

JavaScript array comes with methods built-in that make them act like a stack.

The push method lets us add items to the end of the array.

And the pop method lets us remove the last item from the array.

For instance, we can create a stack by writing:

const stack = []
const pushed = stack.push(1, 2)
console.log(stack)
const popped = stack.pop()
console.log(stack, pushed, popped)

The push method lets us append the items that we passed in as arguments into the stack array.

And it returns the last item that’s been appended to the array.

Therefore, pushed is 2.

The pop method lets us remove the last item from thr stack array.

And it returns the popped item.

So popped is 2 and that’s what’s removed from the array.

So stack is [1, 2] when logged from the first console log.

And the 2nd console log will log [1] as the value of stack .

JavaScript Queue Methods

JavaScript arrays also comes with methods that lets us use them as queues.

We use the push method to append items to the queue as we do with stacks.

And we can use the shift method to remove the first item in the array.

For instance, we can write:

const queue = []
const pushed = queue.push(1, 2)
console.log(queue)
const shifted = queue.shift()
console.log(queue, pushed, shifted)

Therefore, the first console log logs [1, 2] as the value of queue .

And in the 2nd console log, queue is [2] .

pushed is 2 and shifted is 1.

shift returns the element that’s added to the beginning of the array.

Size

To get the size of either data structure, we can just use the length property.

So we can log stack.length and queue.length respectively to get their sizes.

Conclusion

We can implement a stack or a queue with JavaScript by using native array methods.

And we get their sizes with the length property.

Categories
JavaScript Answers

How to Strip All Non-Numeric Characters from a String in JavaScript?

Stripping all non-numeric characters from a string is something that we do sometimes in our JavaScript apps.

In this article, we’ll look at how to strip all non-numeric characters from a string with JavaScript.

String.prototype.replace

To strip all non-numeric characters from a string in JavaScript, we can use the string replace method to find all non-numeric characters and replace them with empty strings.

For instance, we can write:

const str = 'abc123'
const newStr = str.replace(/D/g, '');
console.log(newStr)

to call replace with a regex to get all non-numeric characters and replace them with an empty string.

D mean non-numeric characters.

And g means we search for all instances of the given pattern in the string.

Therefore, newStr is '123' .

Also, we can use the 0-9 pattern to search for digits. so we can write:

const str = 'abc123'
const newStr = str.replace(/[^0-9]/g, '');
console.log(newStr)

And so we get the same result as the previous example.

To leave decimal points and negative signs in the string, we can do a more precise replacement by writing:

const str = 'abc123.45'
const newStr = str.replace(/[^d.-]/g, '');
console.log(newStr)

^d.- means we search for anything other than digits, decimal points, and the negative sign and replace them all with empty strings.

So newStr is ‘123.45’ .

Conclusion

We can use the string’s replace instance method to strip all non-numeric characters from a string with JavaScript.

Categories
JavaScript Answers

How to Get the Difference Between Two Arrays in JavaScript?

Sometimes we need to get the difference between 2 JavaScript arrays.

The difference is the item in one array that’s not in the other.

In this article, we’ll look at how to get various kinds of differences between 2 arrays in JavaScript.

Intersection

The intersection between 2 arrays is a set of items that are in both arrays.

To get the intersection, we can use the filter method.

We can write:

const arr1 = ['a', 'b'];
const arr2 = ['a', 'b', 'c', 'd'];
const intersection = arr1.filter(x => arr2.includes(x));
console.log(intersection)

to computer the intersection.

We have 2 arrays, arr1 and arr2 .

And we compute the intersection by calling filter on arr1 with a callback that checks whether the item x from arr1 is also included with arr2 .

We can switch arr1 and arr2 in the 3rd line and get the same result.

For instance, we can write:

const arr1 = ['a', 'b'];
const arr2 = ['a', 'b', 'c', 'd'];
const intersection = arr2.filter(x => arr1.includes(x));
console.log(intersection)

In both cases, intersection is [“a”, “b”] .

Difference Between 2 Arrays

The difference between 2 arrays is an array of all the items that are available in one array but not the other.

For instance, if we have arr1 and arr2 like we have above, we can get all the items from arr2 that isn’t in arr1 by writing:

const arr1 = ['a', 'b'];
const arr2 = ['a', 'b', 'c', 'd'];
const intersection = arr2.filter(x => !arr1.includes(x));
console.log(intersection)

All we did is change the filter callback to check whether item x in arr2 is included in arr1 or not.

If they aren’t then we include it in the intersection array.

Therefore, intersection is [“c”, “d”] .

Symmetric Difference Between 2 Arrays

The symmetric difference between 2 arrays is the set of items that are in either array but not both.

To compute the symmetric difference, we can write:

const arr1 = ['a', 'b', 'e'];
const arr2 = ['a', 'b', 'c', 'd'];
const symDiff = [...new Set([...arr1, ...arr2])].filter(x => (!arr1.includes(x) && arr2.includes(x)) || (arr1.includes(x) && !arr2.includes(x)))
console.log(symDiff)

We put all the array items into a set by passing an array with both the entries from arr1 and arr2 in it into the Set constructor.

This will remove any duplicate elements from the combined arrays.

Then we convert the set back to an array with the outer spread operator.

And then we call filter on that with:

(!arr1.includes(x) && arr2.includes(x)) || (arr1.includes(x) && !arr2.includes(x))

returned by the callback to get all the elements that are only in arr1 or only in arr2 .

Therefore, symDiff should be [“e”, “c”, “d”] .

Conclusion

We can compute various kinds of differences between arrays with sets and array methods.

Categories
JavaScript Answers

How to Pass Arguments to the JavaScript setTimeout Function’s Callback?

The setTimeout function lets us run JavaScript code after a delay in milliseconds.

In this article, we’ll look at how we can pass in arguments to the JavaScript setTimeout function.

Call setTimeout with More Argumemts

One way to pass arguments to the setTimeout function’s callback is to pass them in after the 2nd argument of setTimeout .

For instance, we can write:

setTimeout((greeting, name) => {  
  console.log(greeting, name)  
}, 1000, 'hello', 'jane')

We have a callback that takes the greeting and name parameters.

And we have the 'hello' and 'jane' arguments after the 2nd argument.

They’ll get passed into the callback in the same order.

So the console log should log hello jane .

Use the bind Method

The bind method lets us return a function with the arguments we want passed in.

So we can use the function returned by bind as the callback instead.

For instance, we can write:

const greet = (greeting, name) => {  
  console.log(greeting, name)  
}  
setTimeout(greet.bind(undefined, 'hello', 'jane'), 1000)

to call greet with the arguments that we pass into bind with setTimeout .

The 2nd and subsequent arguments of bind are passed into the greet function.

So we get the same result as before.

Call the Function in the Callback

Another way we can pass arguments into the setTimeout callback is to call the function we want in the callback.

For instance, we can write:

const greet = (greeting, name) => {  
  console.log(greeting, name)  
}  
setTimeout(() => {  
  greet('hello', 'jane')  
}, 1000)

Instead of trying to pass the greet function into setTimeout directly, we call greet in the callback with the arguments that we want instead.

This gives us the same results as before.

Conclusion

There’re several ways to pass in arguments to the setTimeout callback.

We can transform the callback with bind , or we can pass in the arguments directly to setTimeout .

Also, we can call the function we want in the callback.

Categories
JavaScript Answers

How to Create a File in Memory for Users to Download on Client Side with JavaScript?

Sometimes, we may want to let users download files that aren’t stored on a server.

The data may only be available on the client-side and we want to let users download time.

In this article, we’ll look at how to create a file in memory for users to download on the client-side with JavaScript.

Setting a Tag’s href Attribute to a Base64 String

We can set an a tag’s href attribute’s value to a base64 string.

This way the data will be downloaded to the user’s computer.

For instance, we can add a text file for the user to download by writing:

<a href="data:application/octet-stream;charset=utf-16le;base64,//5mAG8AbwAgAGIAYQByAAoA">text file</a>

href is set to a base64 string.

It consists of the MIME type, which is application/octet-stream .

And the part after the double slash is the encoded text content.

Create File to Download with JavaScript

We can also create the file to download with JavaScript.

For instance, we can write the following HTML:

<button>
  download
</button>

Then we can create a function to let us download content by writing

const download = (filename, text) => {
  const element = document.createElement('a');
  element.setAttribute('href', `data:text/plain;charset=utf-8,${encodeURIComponent(text)}`);
  element.setAttribute('download', filename);
  element.style.display = 'none';
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);
}

const button = document.querySelector('button')
button.addEventListener('click', () => {
  download('file.txt', 'foo bar')
})

In the download function, we get the filename and text parameter values.

Then in the function, we create the a element with createElement .

It’ll be invisible.

Next, we set the href attribute value of it to the content we want to the user to get, which is a base64 string with the encoded text value.

Then we set the download attribute to the filename so the file will be downloaded with the given filename.

Next, we set display style to 'none' so that it’s visible.

And then we append the a element to the body with appendChild .

To download the file, we call click to click on the invisible a element.

And finally, we call removeChild to remove the invisible a element.

Then we get the button with querySelector .

And we call addEventListener on it to add a click listener.

And in the callback, we call download with the filename and content.

Also, we can use createObjectURL to create the base64 string:

const download = (filename, text) => {
  const element = document.createElement('a');
  element.setAttribute('href', window.URL.createObjectURL(new Blob([text], {
    type: 'text/plain'
  })));
  element.setAttribute('download', filename);
  element.style.display = 'none';
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);
}

const button = document.querySelector('button')
button.addEventListener('click', () => {
  download('file.txt', 'foo bar')
})

Conclusion

We can use base64 strings with a elements to let users download data that are only available on the client side.