Creating this site I used this snippet so much that it became a util function. Super simple and an absolute godsend when it came to working with Remix.
export const toSlug = (title: string) =>
title
.toLowerCase()
// remove any spaces from the beginning and end of the string
.trim()
// replace any spaces with a dash
.replace(/ /g, '-')
// replace any characters that aren't numbers letters dashes or slashes
.replace(/[^a-z0-9-\/]/g, '')
I hate having to think about converting dates into a human readable formate so I created a quick util function.
export const toReadableDate = (date: Date) => {
const dateOptions: Intl.DateTimeFormatOptions = {
year: 'numeric',
month: 'long',
day: 'numeric',
}
return new Date(date).toLocaleDateString('en-US', dateOptions)
}
In the future something like this will become even easier using JavaScript's proposed Temporal API
Because sometime you just need to chunk some stuff.
const chunk = (arr, size) =>
Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
arr.slice(i * size, i * size + size)
);
Introduced in ES6 we can now easily flatten multi dimensional arrays. Gone are the days of having to create our own solution (taken from stackoverflow).
// This method accepts one argument to choose the depth of the flattening
const multiDimensionalArray = [
[1, 2],
[3, 4],
[5, 6],
];
const flattenedArray = multiDimensionalArray.flat(); // [1, 2, 3, 4, 5, 6]
A pretty neat solution, by leveraging ES6 Object destructuring assignment we can immutably remove properties.
const item = {
id: 1,
price: 50,
image: 'item.jpeg',
};
const { id, ...item2 } = item;
// now item 2 doesnt have an id property
console.log(item2);
More than anything it's going to save you some heaps of typing, it's a neat solution for something that has plagued developers sanity for a while now. If the expression short circuits (the values doesn't exist) then undefined will be returned.
// Instead of something like
const city = user && user.address && user.address.city;
// We can do
const city = user?.address?.city;
Simple, elegant and it will save you a bunch of time. No more mapping or filtering involved.
myArray.find((x) => x.id === '45').author;
Sometimes when using API's or text from the document special characters are encoded into HTML entities. We can take advantage of the textarea
tag to decode these strings for us!
export const decodeHtmlEntities = (html) => {
var textArea = document.createElement('textarea');
textArea.innerHTML = html;
let decodedHTML = textArea.value;
textArea.remove();
return decodedHTML;
};
Need to easily remove duplicate values from an array? Use this performant one liner:
const dedupedArray = [...new Set(myArray)]
Sometimes you need to know whether an Object
is empty or not. This lil` snippet will sort you right out, and it's pretty simple too!
function isEmpty(object) {
for (const property in object) {
return false;
}
return true;
}