Snippets

A collection of snippets that I use frequently.

Check if all array elements are equal in JavaScript

If you have an array like

const arr = ["a", "a", "a"]; 

isAllEqual(arr); //true

You can use Set to check if all elements are equal

const isAllEqual = arr => new Set(arr).size == 1;

Add Material Design colors to TailwindCSS

To add Material Design colors to TailwindCSS, just copy the content from this Gist and save it as a .js file. You can find the Gist here:

https://gist.github.com/Posandu/76ac596d64bc66178df4fb583f7a8c88

After that, update your Tailwind CSS configuration like this:

const { colors } = require("file_you_saved.js"); // If you're using CommonJS
// or, if you're using ES6 modules
import { colors } from "file_you_saved.js";

/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    //...
    colors,
  },
};

Alternatively, you can simply copy the object inside the Gist and use it as the colors option in your configuration:

/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    //...
    colors: {}, // Paste the object here
  },
};

Proxies in JavaScript

Proxies in JavaScript allow you to execute a function when reading/setting an object property.

const handler = {
  get: function(target, prop) {
    return `Accessing property: ${prop}`;
  }
};

const obj = { name: "ChatGPT" };
const proxy = new Proxy(obj, handler);

console.log(proxy.name); // Output: "Accessing property: name"

Finding the Maximum Value in an Array using JavaScript

To find the maximum value of an array of integers, we can use the Math.max() function and the spread operator to do it.

let numbers = [1, 2, 3, 4, 5];
let maxValue = Math.max(...numbers);
console.log(maxValue);  // Output: 5

Get the time distance as words in JavaScript

You can use the date-fns library to do that.

import { formatDistanceToNow } from "date-fns";

const timeDistance = (time) => formatDistanceToNow(time, { addSuffix: true });

timeDistance(new Date()); // 1 second ago (results may vary)