Skip to content

Instantly share code, notes, and snippets.

@a-kyselova
Last active November 24, 2023 11:52
Show Gist options
  • Save a-kyselova/5c504724815a5ced24d9e96a6112ce2a to your computer and use it in GitHub Desktop.
Save a-kyselova/5c504724815a5ced24d9e96a6112ce2a to your computer and use it in GitHub Desktop.
one-liners

JS

Awesome JavaScript Snippets (one-liners)

Generate a random number between two values

const randomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

Check if a number is an integer

const isInteger = (num) => Number.isInteger(num);

Check if a value is null or undefined

const isNil = (value) => value == null;

Check if a value is a truthy value

const isTruthy = (value) => Boolean(value);

Check if a value is a falsy value

const isFalsy = (value) => !value;

Check if a value is a valid credit card number

const isCreditCard = (cc) => {
  const regex = /(?:(?<visa>4[0-9]{12}(?:[0-9]{3})?)|(?<mastercard>25[1-7][0-9]{14})|(?<discover>6(?:011|5[0-9]{2})(?:[0-9]{12}))(?<amex>3[47][0-9]{13})|(?(8)^(?:2131|1800|35\d{3})\d{11}$))/;
  return regex.test(cc);
}

Check if a value is an object

const isObject = (value) => value !== null && typeof value === 'object';

Check if a value is a function

const isFunction = (value) => typeof value === 'function';

Remove Duplicates from Array

const removeDuplicates = (array) => [...new Set(array)];

Check if a value is a promise

const isPromise = (promise) => Promise.resolve(promise) === promise;

Check if a value is a valid email address

const isEmail = (email) => {
  const regex = /(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/;
  return regex.test(email);
}

Check if a string ends with a given suffix

const endsWith = (str, suffix) => str.endsWith(suffix);

Check if a string starts with a given prefix

const startsWith = (str, prefix) => str.startsWith(prefix);

Check if a value is a valid URL

const isURL = (url) => {
  const regex = /(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+/;
  return regex.test(url);
}

Check if a value is a valid hexadecimal color code

const isHexColor = (hex) => {
  const regex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
  return regex.test(hex);
}

Check if a value is a valid postal code

const isPostalCode = (postalCode, countryCode) => {
  const regexMap = {
    US: /^([0-9]{5})(?:[-\s]*([0-9]{4}))?$/,
    CA: /^([A-Za-z]\d[A-Za-z][-]?\d[A-Za-z]\d)$/
  };
  const regex = regexMap[countryCode.toUpperCase()];
  return regex ? regex.test(postalCode) : false;
}

Check if a value is a DOM element

const isDOMElement = (value) => value instanceof Element;

Check if a value is a valid CSS length (e.g. 10px, 1em, 50%)

const isCSSLength = (value) => {
  const regex = /^[-+]?(\d*\.)?\d+(em|ex|px|in|cm|mm|pt|pc|%|vw|vh|vmin|vmax)$/;
  return regex.test(value);
}

Check if a value is a valid date string (e.g. 2022-09-01,yyyy/mm/dd, etc.)

const isDateString = (value) => !isNaN(Date.parse(value));

Calculate the factorial of a number

const factorial = (num) => {
if (num < 0) return -1; else if (num === 0) return 1; else return (num * factorial(num-1)); }

Find the maximum value in an array

const max = (array) => Math.max(...array);

Find the minimum value in an array

const min = (array) => Math.min(...array);

Calculate the sum of values in an array

const sum = (array) => array.reduce((acc, val) => acc + val, 0);

Create an array of unique values from an array of objects based on a specific key

const uniqueBy = (array, key) => [...new Map(array.map((obj) => [obj[key], obj])).values()];

Quickly create an array of characters from a string

const string = "abcdefg";
const array = [...string];

Quickly create an object with all the properties and values of another object, but with a different key for each property

const original = {a: 1, b: 2, c: 3};
const mapped = {...original, ...Object.keys(original).reduce((obj, key) => ({...obj, [key.toUpperCase()]: original[key]}), {})};

Quickly create an array of numbers from 1 to 10

const array = [...Array(10).keys()].map(i => i + 1);

Quickly shuffle an array

const shuffle = (array) => array.sort(() => Math.random() - 0.5);

Convert an array-like object (such as a NodeList) to an array

const toArray = (arrayLike) => Array.prototype.slice.call(arrayLike);

Sort Arrays

//Ascending
const sortAscending = (array) => array.sort((a, b) => a - b);

//Descending
const sortDescending = (array) => array.sort((a, b) => b - a);

Debounce a function

const debounce = (fn, time) => {
  let timeout;
  return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => fn.apply(this, args), time);
  };
};

Open a new tab with a given URL

const openTab = (url) => {
  window.open(url, "_blank");
};

Get the difference between two dates

const dateDiff = (date1, date2) => Math.abs(new Date(date1) - new Date(date2));

Generate a random string of a given length

const randomString = (length) => {
  let result = "";
  const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment