A collection of small JS utility functions Jul 09

This is a compilation of nearly 300 compact JavaScript utility functions, designed to streamline common programming tasks and enhance code efficiency. If you don’t want to use libraries such as lodash or underscore (but I urge you to do) then this list might come in handy. It contains very simple functions such as isEmpty, isEven and isOdd to more specialized array and object manipulations, this collection offers a wide range of practical tools for JavaScript developers.

These bite-sized functions serve multiple purposes:

  1. Quick solutions for everyday coding challenges
  2. Learning resources for JavaScript best practices and techniques
  3. Building blocks for larger, more complex applications
  4. Time-savers for repetitive programming tasks

Whether you’re a beginner looking to expand your JavaScript toolkit or an experienced developer seeking to optimize your code, this collection provides valuable, ready-to-use functions that can be easily integrated into various projects.

Well, here’s the list

/* 1. Check if an array is empty */
const isEmpty = (arr) => !arr.length

/* 2. Remove duplicates from an array */
const unique = (arr) => [...new Set(arr)]

/* 3. Get the last item in an array */
const lastItem = (arr) => arr[arr.length - 1]

/* 4. Reverse a string */
const reverseString = (str) => str.split('').reverse().join('')

/* 5. Check if a number is even */
const isEven = (num) => num % 2 === 0

/* 6. Check if a number is odd */
const isOdd = (num) => num % 2 !== 0

/* 7. Generate a random number between two values */
const randomBetween = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min

/* 8. Check if a year is a leap year */
const isLeapYear = (year) => (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0)

/* 9. Shuffle an array */
const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5)

/* 10. Get a random item from an array */
const randomItem = (arr) => arr[Math.floor(Math.random() * arr.length)]

/* 11. Convert a string to an array of words */
const words = (str) => str.match(/\w+/g)

/* 12. Clone an array */
const cloneArray = (arr) => arr.slice()

/* 13. Flatten an array */
const flattenArray = (arr) => arr.flat()

/* 14. Remove falsy values from an array */
const compact = (arr) => arr.filter(Boolean)

/* 15. Get the intersection of two arrays */
const intersection = (arr1, arr2) => arr1.filter(x => arr2.includes(x))

/* 16. Get the union of two arrays */
const union = (arr1, arr2) => [...new Set([...arr1, ...arr2])]

/* 17. Convert array of pairs to an object */
const arrayToObject = (arr) => Object.fromEntries(arr)

/* 18. Convert object to array of pairs */
const objectToArray = (obj) => Object.entries(obj)

/* 19. Merge two objects */
const mergeObjects = (obj1, obj2) => ({ ...obj1, ...obj2 })

/* 20. Convert RGB to hex */
const rgbToHex = (r, g, b) => '#' + [r, g, b].map(x => x.toString(16).padStart(2, '0')).join('')

/* 21. Convert hex to RGB */
const hexToRgb = (hex) => hex.slice(1).match(/.{2}/g).map(x => parseInt(x, 16))

/* 22. Get the day of the year */
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24)

/* 23. Get the number of days in a month */
const daysInMonth = (year, month) => new Date(year, month, 0).getDate()

/* 24. Format date as YYYY-MM-DD */
const formatDate = (date) => date.toISOString().split('T')[0]

/* 25. Capitalize the first letter of each word */
const capitalizeWords = (str) => str.replace(/\b\w/g, c => c.toUpperCase())

/* 26. Generate a random string */
const randomString = (length) => Math.random().toString(36).substr(2, length)

/* 27. Check if a string contains a substring */
const contains = (str, substr) => str.indexOf(substr) !== -1

/* 28. Convert a string to kebab case */
const toKebabCase = (str) => str.trim().replace(/[\s_]+/g, '-').toLowerCase()

/* 29. Convert a string to snake case */
const toSnakeCase = (str) => str.trim().replace(/[\s-]+/g, '_').toLowerCase()

/* 30. Convert a string to camel case */
const toCamelCase = (str) => str.trim().replace(/[-_](.)/g, (_, c) => c.toUpperCase())

/* 31. Repeat a string n times */
const repeat = (str, n) => str.repeat(n)

/* 32. Trim whitespace from both sides */
const trim = (str) => str.trim()

/* 33. Convert a string to an array */
const toArray = (str) => [...str]

/* 34. Count the occurrences of a substring */
const countOccurrences = (str, subStr) => str.split(subStr).length - 1

/* 35. Find the index of a substring */
const indexOfSub = (str, subStr) => str.indexOf(subStr)

/* 36. Replace all occurrences of a substring */
const replaceAll = (str, subStr, newStr) => str.split(subStr).join(newStr)

/* 37. Check if a string starts with a substring */
const startsWith = (str, subStr) => str.startsWith(subStr)

/* 38. Check if a string ends with a substring */
const endsWith = (str, subStr) => str.endsWith(subStr)

/* 39. Uppercase the first letter */
const capitalizeFirst = (str) => str.charAt(0).toUpperCase() + str.slice(1)

/* 40. Lowercase the first letter */
const decapitalizeFirst = (str) => str.charAt(0).toLowerCase() + str.slice(1)

/* 41. Check if a value is a number */
const isNumber = (val) => !isNaN(val)

/* 42. Convert a number to a string */
const numberToString = (num) => num.toString()

/* 43. Convert a string to a number */
const stringToNumber = (str) => +str

/* 44. Get the absolute value of a number */
const abs = (num) => Math.abs(num)

/* 45. Round a number to the nearest integer */
const round = (num) => Math.round(num)

/* 46. Round a number down */
const floor = (num) => Math.floor(num)

/* 47. Round a number up */
const ceil = (num) => Math.ceil(num)

/* 48. Get the maximum number in an array */
const max = (arr) => Math.max(...arr)

/* 49. Get the minimum number in an array */
const min = (arr) => Math.min(...arr)

/* 50. Get the sum of an array */
const sum = (arr) => arr.reduce((acc, num) => acc + num, 0)

/* 51. Get the average of an array */
const average = (arr) => sum(arr) / arr.length

/* 52. Convert degrees to radians */
const degreesToRadians = (deg) => deg * (Math.PI / 180)

/* 53. Convert radians to degrees */
const radiansToDegrees = (rad) => rad * (180 / Math.PI)

/* 54. Generate a UUID */
const uuid = () => 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => (c === 'x' ? Math.random() * 16 : (Math.random() * 4 + 8) % 16).toString(16))

/* 55. Debounce a function */
const debounce = (fn, delay) => { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); }; }

/* 56. Throttle a function */
const throttle = (fn, limit) => { let lastFunc, lastRan; return function() { const context = this, args = arguments; if (!lastRan) { fn.apply(context, args); lastRan = Date.now(); } else { clearTimeout(lastFunc); lastFunc = setTimeout(function() { if (Date.now() - lastRan >= limit) { fn.apply(context, args); lastRan = Date.now(); } }, limit - (Date.now() - lastRan)); } }; }

/* 57. Convert a string to title case */
const toTitleCase = (str) => str.replace(/\w\S*/g, (txt) => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase())

/* 58. Case insensitive string comparison */
const caseInsensitiveCompare = (str1, str2) => str1.toLowerCase() === str2.toLowerCase()

/* 59. Validate an email */
const isValidEmail = (email) => /\S+@\S+\.\S+/.test(email)

/* 60. Validate a URL */
const isValidUrl = (str) => /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/.test(str)

/* 61. Sleep for a specified time */
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms))

/* 62. Convert a date to timestamp */
const toTimestamp = (date) => Date.parse(date)

/* 63. Get current timestamp */
const currentTimestamp = () => Date.now()

/* 64. Clear all cookies */
const clearCookies = () => document.cookie.split(';').forEach(c => document.cookie = c.trim().split('=')[0] + '=;expires=Thu, 01 Jan 1970 00:00:00 UTC')

/* 65. Get a random color */
const randomColor = () => '#' + Math.floor(Math.random() * 16777215).toString(16)

/* 66. Format number with commas */
const formatNumber = (num) => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")

/* 67. Compute Fibonacci sequence */
const fibonacci = (n) => n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2)

/* 68. Check if a value is an array */
const isArray = (val) => Array.isArray(val)

/* 69. Generate a range of numbers */
const range = (start, end) => [...Array(end - start + 1).keys()].map(i => i + start)

/* 70. Find the factorial of a number */
const factorial = (n) => n <= 1 ? 1 : n * factorial(n - 1)

/* 71. Create a shallow copy of an object */
const shallowCopy = (obj) => ({ ...obj })

/* 72. Create a deep copy of an object */
const deepCopy = (obj) => JSON.parse(JSON.stringify(obj))

/* 73. Check if an object is empty */
const isEmptyObject = (obj) => Object.keys(obj).length === 0

/* 74. Get the length of an object */
const objectLength = (obj) => Object.keys(obj).length

/* 75. Get a random boolean value */
const randomBoolean = () => Math.random() >= 0.5

/* 76. Generate a random hex color */
const randomHexColor = () => '#' + Math.random().toString(16).slice(2, 8).padEnd(6, '0')

/* 77. Calculate the HCF of two numbers */
const hcf = (x, y) => !y ? x : hcf(y, x % y)

/* 78. Calculate the LCM of two numbers */
const lcm = (x, y) => !x || !y ? 0 : Math.abs((x * y) / hcf(x, y))

/* 79. Convert Celsius to Fahrenheit */
const celsiusToFahrenheit = (c) => (c * 9/5) + 32

/* 80. Convert Fahrenheit to Celsius */
const fahrenheitToCelsius = (f) => (f - 32) * 5/9

/* 81. Compute the power of a number */
const power = (base, exp) => Math.pow(base, exp)

/* 82. Check if an object has a property */
const hasProperty = (obj, prop) => obj.hasOwnProperty(prop)

/* 83. Encode a URL */
const encodeURL = (url) => encodeURIComponent(url)

/* 84. Decode a URL */
const decodeURL = (url) => decodeURIComponent(url)

/* 85. Strip HTML tags from a string */
const stripHTML = (str) => str.replace(/<[^>]*>?/gm, '')

/* 86. Check if a string is palindrome */
const isPalindrome = (str) => str === str.split('').reverse().join('')

/* 87. Get query params from URL */
const getQueryParams = (url) => Object.fromEntries(new URL(url).searchParams)

/* 88. Merge two arrays */
const mergeArrays = (arr1, arr2) => [...arr1, ...arr2]

/* 89. Find the nth Fibonacci number */
const nthFibonacci = (n, a = 1, b = 1) => n <= 2 ? b : nthFibonacci(n - 1, b, a + b)

/* 90. Find the square root */
const sqrt = (num) => Math.sqrt(num)

/* 91. Calculate the distance between two points */
const distance = (x1, y1, x2, y2) => Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)

/* 92. Get current date and time */
const currentDateTime = () => new Date().toLocaleString()

/* 93. Get the type of a variable */
const getType = (val) => typeof val

/* 94. Check if a value is an object */
const isObject = (val) => val && typeof val === 'object' && val.constructor === Object

/* 95. Check if a value is a function */
const isFunction = (val) => val && typeof val === 'function'

/* 96. Convert a value to boolean */
const toBoolean = (val) => !!val

/* 97. Parse a JSON string */
const parseJSON = (str) => JSON.parse(str)

/* 98. Join array elements into a string */
const joinArray = (arr, sep = ',') => arr.join(sep)

/* 99. Capitalize the first word */
const capitalizeFirstWord = (str) => str.replace(/^\w/, c => c.toUpperCase())

/* 100. Calculate body mass index (BMI) */
const bmi = (weight, height) => (weight / (height ** 2)).toFixed(1)

/* 101. Find the longest word in a string */
const longestWord = (str) => str.split(' ').sort((a, b) => b.length - a.length)[0]

/* 102. Find the shortest word in a string */
const shortestWord = (str) => str.split(' ').sort((a, b) => a.length - b.length)[0]

/* 103. Check if two arrays are equal */
const arraysEqual = (arr1, arr2) => JSON.stringify(arr1) === JSON.stringify(arr2)

/* 104. Get the difference between two arrays */
const arrayDifference = (arr1, arr2) => arr1.filter(x => !arr2.includes(x))

/* 105. Get the symmetric difference of two arrays */
const symmetricDifference = (arr1, arr2) => arr1.filter(x => !arr2.includes(x)).concat(arr2.filter(x => !arr1.includes(x)))

/* 106. Get the common elements in two arrays */
const commonElements = (arr1, arr2) => arr1.filter(x => arr2.includes(x))

/* 107. Remove specific element from an array */
const without = (arr, ...args) => arr.filter(x => !args.includes(x))

/* 108. Check if a string is empty */
const isEmptyString = (str) => str.trim().length === 0

/* 109. Convert a string to an array of characters */
const stringToCharArray = (str) => str.split('')

/* 110. Split a string by a delimiter */
const splitByDelimiter = (str, delim) => str.split(delim)

/* 111. Remove whitespace from a string */
const removeWhitespace = (str) => str.replace(/\s/g, '')

/* 112. Repeat a string n times */
const repeatString = (str, num) => str.repeat(num)

/* 113. Get the index of an element in an array */
const indexOfElement = (arr, el) => arr.indexOf(el)

/* 114. Remove the first element of an array */
const removeFirst = (arr) => arr.slice(1)

/* 115. Remove the last element of an array */
const removeLast = (arr) => arr.slice(0, -1)

/* 116. Find the number of digits in a number */
const numDigits = (num) => num.toString().length

/* 117. Calculate compound interest */
const compoundInterest = (p, r, t, n) => p * (1 + r / n) ** (n * t)

/* 118. Check if a string is a valid date */
const isValidDate = (date) => !isNaN(Date.parse(date))

/* 119. Convert a Unix timestamp to a date */
const timestampToDate = (timestamp) => new Date(timestamp)

/* 120. Convert a date to a Unix timestamp */
const dateToTimestamp = (date) => date.getTime()

/* 121. Get the current year */
const currentYear = () => new Date().getFullYear()

/* 122. Get the current month */
const currentMonth = () => new Date().getMonth() + 1

/* 123. Get the current day */
const currentDay = () => new Date().getDate()

/* 124. Convert seconds to hours, minutes, and seconds */
const secondsToHMS = (sec) => { const h = Math.floor(sec / 3600); const m = Math.floor((sec % 3600) / 60); const s = sec % 60; return `${h}h ${m}m ${s}s`; }

/* 125. Count the number of vowels in a string */
const countVowels = (str) => str.match(/[aeiou]/gi)?.length || 0

/* 126. Check if a string is numeric */
const isNumeric = (str) => !isNaN(str)

/* 127. Convert a number to binary */
const toBinary = (num) => num.toString(2)

/* 128. Convert a binary number to decimal */
const binaryToDecimal = (bin) => parseInt(bin, 2)

/* 129. Convert a number to hexadecimal */
const toHex = (num) => num.toString(16)

/* 130. Convert a hexadecimal number to decimal */
const hexToDecimal = (hex) => parseInt(hex, 16)

/* 131. Round a number to n decimal places */
const roundTo = (num, places) => +num.toFixed(places)

/* 132. Calculate the hypotenuse of a right triangle */
const hypotenuse = (a, b) => Math.sqrt(a ** 2 + b ** 2)

/* 133. Calculate the area of a circle */
const areaOfCircle = (radius) => Math.PI * radius ** 2

/* 134. Calculate the circumference of a circle */
const circumference = (radius) => 2 * Math.PI * radius

/* 135. Calculate the area of a rectangle */
const areaOfRectangle = (length, width) => length * width

/* 136. Calculate the perimeter of a rectangle */
const perimeter = (length, width) => 2 * (length + width)

/* 137. Calculate the area of a triangle */
const areaOfTriangle = (base, height) => (base * height) / 2

/* 138. Check if a string is a URL */
const isUrl = (str) => /^(http|https):\/\/[^\s$.?#].[^\s]*$/.test(str)

/* 139. Truncate a string to a specified length */
const truncate = (str, len) => str.length > len ? str.slice(0, len) + '...' : str

/* 140. Get the first n elements of an array */
const firstElements = (arr, n) => arr.slice(0, n)

/* 141. Get the last n elements of an array */
const lastElements = (arr, n) => arr.slice(-n)

/* 142. Check if an object is a date */
const isDate = (val) => val instanceof Date

/* 143. Find the nth root of a number */
const nthRoot = (num, root) => Math.pow(num, 1 / root)

/* 144. Calculate the sum of even numbers in an array */
const sumOfEvens = (arr) => arr.filter(n => n % 2 === 0).reduce((a, b) => a + b, 0)

/* 145. Calculate the sum of odd numbers in an array */
const sumOfOdds = (arr) => arr.filter(n => n % 2 !== 0).reduce((a, b) => a + b, 0)

/* 146. Get the median of an array */
const median = (arr) => { const sorted = arr.slice().sort((a, b) => a - b); const mid = Math.floor(sorted.length / 2); return sorted.length % 2 !== 0 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; }

/* 147. Get the mode of an array */
const mode = (arr) => arr.reduce((a, b, i, ar) => ar.filter(v => v === a).length >= ar.filter(v => v === b).length ? a : b, null)

/* 148. Calculate the variance of an array */
const variance = (arr) => { const mean = arr.reduce((a, b) => a + b, 0) / arr.length; return arr.map(x => (x - mean) ** 2).reduce((a, b) => a + b, 0) / arr.length; }

/* 149. Calculate the standard deviation of an array */
const standardDeviation = (arr) => Math.sqrt(variance(arr))

/* 150. Check if a number is prime */
const isPrime = (num) => { for (let i = 2, s = Math.sqrt(num); i <= s; i++) if (num % i === 0) return false; return num > 1; }

/* 151. Find the greatest common divisor (GCD) */
const gcd = (a, b) => !b ? a : gcd(b, a % b)

/* 152. Get a random float between two values */
const randomFloat = (min, max) => Math.random() * (max - min) + min

/* 153. Interpolate between two values */
const interpolate = (start, end, factor) => start + (end - start) * factor

/* 154. Get the current timestamp in seconds */
const timestampInSeconds = () => Math.floor(Date.now() / 1000)

/* 155. Convert a string to lowercase */
const toLowerCase = (str) => str.toLowerCase()

/* 156. Convert a string to uppercase */
const toUpperCase = (str) => str.toUpperCase()

/* 157. Find the square of a number */
const square = (num) => num ** 2

/* 158. Find the cube of a number */
const cube = (num) => num ** 3

/* 159. Convert an array to a string with a delimiter */
const arrayToString = (arr, delim = ',') => arr.join(delim)

/* 160. Get unique values from an array */
const uniqueValues = (arr) => Array.from(new Set(arr))

/* 161. Check if all array elements satisfy a condition */
const allElements = (arr, fn) => arr.every(fn)

/* 162. Repeat an array n times */
const repeatArray = (arr, num) => Array(num).fill(arr).flat()

/* 163. Flatten a nested array */
const flatten = (arr) => arr.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), [])

/* 164. Get the keys of an object */
const getObjectKeys = (obj) => Object.keys(obj)

/* 165. Get the values of an object */
const getObjectValues = (obj) => Object.values(obj)

/* 166. Get the entries of an object */
const getObjectsEntries = (obj) => Object.entries(obj)

/* 167. Get the average of an array of numbers */
const avg = (arr) => arr.reduce((sum, val) => sum + val, 0) / arr.length

/* 168. Check if a year is a leap year */
const isLeap = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0

/* 169. Get the current day of the week */
const currentDayOfWeek = () => new Date().toLocaleString('en-us', { weekday: 'long' })

/* 170. Get the current month name */
const currentMonthName = () => new Date().toLocaleString('en-us', { month: 'long' })

/* 171. Check if some array elements satisfy a condition */
const someElements = (arr, fn) => arr.some(fn)

/* 172. Sort an array of objects */
const sortByKey = (arr, key) => arr.sort((a, b) => (a[key] > b[key] ? 1 : -1))

/* 173. Format a date as MM/DD/YYYY */
const formatDateMMDDYYYY = (date) => { const d = new Date(date); return `${d.getMonth() + 1}/${d.getDate()}/${d.getFullYear()}`; }

/* 174. Add days to a date */
const addDays = (date, days) => { let result = new Date(date); result.setDate(result.getDate() + days); return result; }

/* 175. Get the number of days between two dates */
const daysBetween = (date1, date2) => Math.abs(Math.floor((date2 - date1) / (1000 * 60 * 60 * 24)))

/* 176. Get the sign of a number */
const sign = (num) => Math.sign(num)

/* 177. Filter an array based on condition */
const filterArray = (arr, fn) => arr.filter(fn)

/* 178. Reduce an array to a single value */
const reduceArray = (arr, fn, init) => arr.reduce(fn, init)

/* 179. Calculate the distance between two points */
const distanceBetweenPoints = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1)

/* 180. Get the hour from a date object */
const getHour = (date) => date.getHours()

/* 181. Get the minute from a date object */
const getMinute = (date) => date.getMinutes()

/* 182. Get the second from a date object */
const getSecond = (date) => date.getSeconds()

/* 183. Get the UTC timestamp */
const getUTCTimestamp = () => Date.now()

/* 184. Shuffle the characters in a string */
const shuffleString = (str) => str.split('').sort(() => 0.5 - Math.random()).join('')

/* 185. Check if an array contains all elements of another array */
const arrayContainsArray = (superset, subset) => subset.every(value => superset.includes(value))

/* 186. Get the file extension from a file name */
const getFileExtension = (filename) => filename.split('.').pop()

/* 187. Pad a string with zeros */
const padWithZeros = (num, places) => String(num).padStart(places, '0')

/* 188. Replace all instances of a substring */
const replaceAllStrings = (str, find, replace) => str.split(find).join(replace)

/* 189. Capitalize the first character of each word */
const capitalizeFirstChar = (str) => str.replace(/\b\w/g, char => char.toUpperCase())

/* 190. Merge two sorted arrays */
const mergeSortedArrays = (arr1, arr2) => [...arr1, ...arr2].sort((a, b) => a - b)

/* 191. Interleave two arrays */
const interleaveArrays = (arr1, arr2) => arr1.flatMap((val, index) => [val, arr2[index]])

/* 192. Get the sum of the digits of a number */
const sumDigits = (num) => num.toString().split('').reduce((acc, digit) => acc + parseInt(digit), 0)

/* 193. Remove specific properties from an object */
const removeProperties = (obj, props) => Object.fromEntries(Object.entries(obj).filter(([key]) => !props.includes(key)))

/* 194. Compare two objects */
const compareObjects = (obj1, obj2) => JSON.stringify(obj1) === JSON.stringify(obj2)

/* 195. Calculate the elapsed time between two dates */
const elapsedTimeBetweenDates = (start, end) => { const diff = end - start; return { hours: Math.floor(diff / 36e5), minutes: Math.floor((diff % 36e5) / 60000), seconds: Math.floor((diff % 60000) / 1000) }; }

/* 196. Create an array of n elements */
const createArray = (length, val) => Array.from({ length }, () => val)

/* 197. Resize an array */
const resizeArray = (arr, newSize, defaultValue = null) => [...arr, ...Array(Math.max(newSize - arr.length, 0)).fill(defaultValue)].slice(0, newSize)

/* 198. Get every nth element of an array */
const everyNth = (arr, nth) => arr.filter((_, i) => i % nth === nth - 1)

/* 199. Check if a string is a palindrome */
const palindromeCheck = (str) => str === str.split('').reverse().join('')

/* 200. Get all combinations of an array */
const combinations = (arr) => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]])

/* 201. Check if a value is a boolean */
const isBoolean = (val) => typeof val === 'boolean'

/* 202. Check if a value is null */
const isNull = (val) => val === null

/* 203. Check if a value is undefined */
const isUndefined = (val) => typeof val === 'undefined'

/* 204. Check if a value is NaN */
const isNaNValue = (val) => Number.isNaN(val)

/* 205. Check if a value is an integer */
const isInteger = (val) => Number.isInteger(val)

/* 206. Map values of an array */
const mapArray = (arr, fn) => arr.map(fn)

/* 207. Check if an object has nested properties */
const hasNestedProperty = (obj, path) => path.split('.').reduce((o, p) => o ? o[p] : null, obj) !== null

/* 208. Check if a number is positive */
const isPositive = (num) => num > 0

/* 209. Check if a number is negative */
const isNegative = (num) => num < 0

/* 210. Toggle a boolean value */
const toggleBoolean = (bool) => !bool

/* 211. Check if a value is a string */
const isString = (val) => typeof val === 'string'

/* 212. Remove punctuation from a string */
const removePunctuation = (str) => str.replace(/[.,\/#!$%\^&\*;:{}=\-_~()]/g, "")

/* 213. Replace spaces with underscores */
const spacesToUnderscores = (str) => str.replace(/\s/g, '_')

/* 214. Replace underscores with spaces */
const underscoresToSpaces = (str) => str.replace(/_/g, ' ')

/* 215. Replace spaces with hyphens */
const spacesToHyphens = (str) => str.replace(/\s/g, '-')

/* 216. Replace hyphens with spaces */
const hyphensToSpaces = (str) => str.replace(/-/g, ' ')

/* 217. Unique elements in an array */
const uniqueElements = (arr) => [...new Set(arr)]

/* 218. Convert a string to pascal case */
const toPascalCase = (str) => str.replace(/(\w)(\w*)/g, function(g0,g1,g2){ return g1.toUpperCase() + g2.toLowerCase(); })

/* 219. Swap values in an array */
const swapValues = (arr, idx1, idx2) => ([arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]], arr)

/* 220. Move an element within an array */
const moveElement = (arr, from, to) => (arr.splice(to, 0, arr.splice(from, 1)[0]), arr)

/* 221. Split a string into an array of words */
const splitIntoWords = (str) => str.split(/\s+/)

/* 222. Merge an array of words into a string */
const mergeWords = (arr) => arr.join(' ')

/* 223. Get a timestamp for a date */
const getTimestamp = (date) => new Date(date).getTime()

/* 224. Format a date as DD/MM/YYYY */
const formatDateDDMMYYYY = (date) => {  const d = new Date(date); return `${d.getDate()}/${d.getMonth() + 1}/${d.getFullYear()}`; }

/* 225. Compare two dates */
const compareDates = (date1, date2) => new Date(date1) - new Date(date2)

/* 226. Check if a value is a symbol */
const isSymbol = (val) => typeof val === 'symbol'

/* 227. Create a set from an array */
const arrayToSet = (arr) => new Set(arr)

/* 228. Create an array from a set */
const setToArray = (set) => Array.from(set)

/* 229. Get the first element of a set */
const firstSetElement = (set) => set.values().next().value

/* 230. Get the last element of a set */
const lastSetElement = (set) => [...set].pop()

/* 231. Check if a set contains an element */
const setContains = (set, el) => set.has(el)

/* 232. Get the union of two sets */
const unionSets = (set1, set2) => new Set([...set1, ...set2])

/* 233. Get the intersection of two sets */
const intersectSets = (set1, set2) => new Set([...set1].filter(x => set2.has(x)))

/* 234. Get the difference of two sets */
const differenceSets = (set1, set2) => new Set([...set1].filter(x => !set2.has(x)))

/* 235. Get the symmetric difference of two sets */
const symmetricDifferenceSets = (set1, set2) => new Set([...set1].filter(x => !set2.has(x)).concat([...set2].filter(x => !set1.has(x))))

/* 236. Clear all elements of a set */
const clearSet = (set) => set.clear()

/* 237. Get the length of a set */
const setLength = (set) => set.size

/* 238. Check if a value is an instance of a class */
const isInstance = (val, cls) => val instanceof cls

/* 239. Get the maximum value in a set */
const maxSetValue = (set) => Math.max(...set)

/* 240. Get the minimum value in a set */
const minSetValue = (set) => Math.min(...set)

/* 241. Convert a set to a string */
const setToString = (set) => [...set].join(', ')

/* 242. Check if an array contains duplicate values */
const hasDuplicates = (arr) => new Set(arr).size !== arr.length

/* 243. Find duplicates in an array */
const findDuplicates = (arr) => arr.filter((item, index) => arr.indexOf(item) !== index)

/* 244. Remove duplicates from an array */
const removeDuplicates = (arr) => [...new Set(arr)]

/* 245. Check if an array is a subset of another array */
const isSubset = (arr1, arr2) => arr2.every(val => arr1.includes(val))

/* 246. Get the union of two arrays */
const unionArrays = (arr1, arr2) => [...new Set([...arr1, ...arr2])]

/* 247. Get the intersection of two arrays */
const intersectArrays = (arr1, arr2) => arr1.filter(x => arr2.includes(x))

/* 248. Get the difference of two arrays */
const differenceArrays = (arr1, arr2) => arr1.filter(x => !arr2.includes(x))

/* 249. Get the symmetric difference of two arrays */
const symmetricDifferenceArrays = (arr1, arr2) => arr1.filter(x => !arr2.includes(x)).concat(arr2.filter(x => !arr1.includes(x)))

/* 250. Create a Map from an array of pairs */
const arrayToMap = (arr) => new Map(arr)

/* 251. Create an array of pairs from a Map */
const mapToArray = (map) => Array.from(map.entries())

/* 252. Get the keys of a Map */
const getMapKeys = (map) => Array.from(map.keys())

/* 253. Get the values of a Map */
const getMapValues = (map) => Array.from(map.values())

/* 254. Get the entries of a Map */
const getMapEntries = (map) => Array.from(map.entries())

/* 255. Check if a Map contains a key */
const mapContainsKey = (map, key) => map.has(key)

/* 256. Get the value of a key in a Map */
const getMapValue = (map, key) => map.get(key)

/* 257. Set a key-value pair in a Map */
const setMapValue = (map, key, value) => map.set(key, value)

/* 258. Delete a key-value pair in a Map */
const deleteMapValue = (map, key) => map.delete(key)

/* 259. Clear all key-value pairs in a Map */
const clearMap = (map) => map.clear()

/* 260. Get the size of a Map */
const mapSize = (map) => map.size

/* 261. Merge two Maps */
const mergeMaps = (map1, map2) => new Map([...map1, ...map2])

/* 262. Clone a Map */
const cloneMap = (map) => new Map(map)

/* 263. Filter a Map */
const filterMap = (map, fn) => new Map([...map].filter(fn))

/* 264. Transform a Map into an object */
const mapToObject = (map) => Object.fromEntries(map)

/* 265. Transform an object into a Map */
const objectToMap = (obj) => new Map(Object.entries(obj))

/* 266. Check if two Maps are equal */
const mapsEqual = (map1, map2) => map1.size === map2.size && [...map1.entries()].every(([key, val]) => val === map2.get(key))

/* 267. Reverse the key-value pairs in a Map */
const reverseMap = (map) => new Map([...map].map(([key, val]) => [val, key]))

/* 268. Sort a Map by keys */
const sortMapByKey = (map) => new Map([...map.entries()].sort())

/* 269. Sort a Map by values */
const sortMapByValue = (map) => new Map([...map.entries()].sort((a, b) => a[1] - b[1]))

/* 270. Get a random value from a Map */
const randomMapValue = (map) => { const values = [...map.values()]; return values[Math.floor(Math.random() * values.length)]; }

/* 271. Invert the key-value pairs of an object */
const invertObject = (obj) => Object.fromEntries(Object.entries(obj).map(([key, val]) => [val, key]))

/* 272. Remove null or undefined properties from an object */
const cleanObject = (obj) => Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null))

/* 273. Get the first key of an object */
const firstObjectKey = (obj) => Object.keys(obj)[0]

/* 274. Get the last key of an object */
const lastObjectKey = (obj) => Object.keys(obj).pop()

/* 275. Deep clone an object */
const deepClone = (obj) => JSON.parse(JSON.stringify(obj))

/* 276. Merge two objects deeply */
const deepMerge = (obj1, obj2) => { const isObject = obj => obj && typeof obj === "object"; return Object.keys(obj2).reduce((acc, key) => { if (Array.isArray(obj1[key]) && Array.isArray(obj2[key])) { acc[key] = obj1[key].concat(...obj2[key]); } else if (isObject(obj1[key]) && isObject(obj2[key])) { acc[key] = deepMerge(obj1[key], obj2[key]); } else { acc[key] = obj2[key]; } return acc; }, { ...obj1 }); }

/* 277. Fill an array with values */
const fillArray = (count, value) => Array(count).fill(value)

/* 278. Check if two objects are deeply equal */
const deepEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b)

/* 279. Find the maximum value in an array of objects */
const maxBy = (arr, key) => arr.reduce((a, b) => (a[key] > b[key] ? a : b))

/* 280. Find the minimum value in an array of objects */
const minBy = (arr, key) => arr.reduce((a, b) => (a[key] < b[key] ? a : b))

/* 281. Randomize the order of elements in an array */
const shuffle = (arr) => arr.sort(() => 0.5 - Math.random())

/* 282. Get a random element from an array */
const randomElement = (arr) => arr[Math.floor(Math.random() * arr.length)]

/* 283. Chunk an array into smaller arrays */
const chunkArray = (arr, size) => { const result = []; while (arr.length) result.push(arr.splice(0, size)); return result; }

/* 284. Flatten a nested array of any depth */
const flattenDeep = (arr) => arr.reduce((a, b) => a.concat(Array.isArray(b) ? flattenDeep(b) : b), [])

/* 285. Compare two strings ignoring case */
const equalsIgnoreCase = (str1, str2) => str1.toLowerCase() === str2.toLowerCase()

/* 286. Zip arrays */
const zip = (...arrays) => Array.from({ length: Math.max(...arrays.map(a => a.length)) }, (_, i) => arrays.map(a => a[i]))

/* 287. Remove falsy values from an array */
const compactArray = (arr) => arr.filter(Boolean)

Enjoy