Skip to content

Instantly share code, notes, and snippets.

@arielivandiaz
Created April 19, 2022 15:20
Show Gist options
  • Save arielivandiaz/d75d8ed139620896c919882669f4c074 to your computer and use it in GitHub Desktop.
Save arielivandiaz/d75d8ed139620896c919882669f4c074 to your computer and use it in GitHub Desktop.
One line important functions
// VARIABLES **************************************************************************
// Swapping Two Variables
[foo, bar] = [bar, foo];
// Conditional asignation
const fullName = name || 'buddy';
// NUMBERS **************************************************************************
// Check if a number is even
const isEven = (num) => num % 2 === 0;
// RANDOM ***************************************************************************
// Random Boolean
const getRandomBoolean = () => Math.random() >= 0.5;
// STRINGS ***************************************************************************
// Reverse String
const stringReverse = str => str.split("").reverse().join("");
// Capitalize a String
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
// Generate a Random ID
const randomID = Math.random().toString(36).substring(2)
// Truncate a String
const truncateString = (string, length) => {
return string.length < length ? string : `${string.slice(0, length - 3)}...`;
}
// ARRAYS ***************************************************************************
// Check if array is empty
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
// Array Averange
const average = arr => arr.reduce((a, b) => a + b) / arr.length;
// Remove Duplicates in an Array
const removeDuplicates = (arr) => [...new Set(arr)];
// Mess / Shuffle Array
const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5);
// Merge multiple arrays
const merge = (a, b) => [...a, ...b];
// Merge multiple arrays and remove duplicates
const merge = [...new Set([...a, ...b])];
// DATES ***************************************************************************
// Get an Array of Past Seven Days
const pastWeek = [...Array(7).keys()].map(days => new Date(Date.now() - 86400000 * days));
// Get the Number of Days Between Two Days
const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000);
// Check if the date is Weekend
const isWeekend = (date) => [0, 6].indexOf(date.getDay()) !== -1;
// Calculate number of days between two dates
const daysDiff = (date, date2) => Math.ceil(Math.abs(date - date2) / 86400000);
// Day number of year
const dayOfYear = (date) =>
Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment