Snippets

A collection of snippets that I use frequently.

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)

Node.js copy to clipboard

We can use the clipboardy npm package to copy text to the clipboard or read the clipboard.

Install it by running npm i clipboardy

Usage:

const clipboardy = require('clipboardy');

// Copy some text to the clipboard
clipboardy.writeSync('Lorem ipsum dolor sit amet');

// Read the text from the clipboard
clipboardy.readSync();

Delete all files in a directory

If you're using Windows you can use this Powershell script

Remove-Item dir\* -Recurse -Force

or if you are a Linux user

rm -r dir/*

Initialize git in a directory

Make sure git is installed. Then run the below command to initialize.

git init
Scroll to Top