Last active
February 22, 2022 23:43
-
-
Save trepichio/15a00915c3de1e987ccbedd15c0ba688 to your computer and use it in GitHub Desktop.
JS One liners
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* If-else functional */ | |
export const conditionally = (config) => (props) => { | |
return config.if(props) ? | |
config.then(props) : config.else(props); | |
}; | |
/* Try-catch functional */ | |
export function tryCatch({ | |
tryer, | |
catcher | |
}) { | |
return (props) => { | |
try { | |
return tryer(props); | |
} catch (e) { | |
return catcher(props, e.message); | |
} | |
}; | |
} | |
/* Deep freeze an object */ | |
function deepFreeze(object) { | |
Object.entries(object).forEach(([key, value]) => { | |
if (value && typeof value === 'object') { | |
deepFreeze(value); | |
} | |
}); | |
return Object.freeze(object); | |
} | |
/* Remove Properties from Object */ | |
export const removePropertiesFromObject = (obj, props) => { | |
props.forEach((prop) => { | |
for (const key in object) { | |
if (key === prop) { | |
delete object[key]; | |
} | |
} | |
}); | |
return obj; | |
} | |
/* Add list of properties and their values (array of tuples) or set them null */ | |
export const addPropertiesToObject = (object, properties) => { | |
properties.forEach(property => { | |
if (property[1]) { | |
object[property[0]] = property[1] | |
} else { | |
object[property[0]] = null | |
} | |
}); | |
return object; | |
} | |
/* Remove all properties with specific value from Object */ | |
export const removePropertiesWithValueFromObject = (object, value) => { | |
for (const key in object) { | |
if (object[key] === value) { | |
delete object[key]; | |
} | |
} | |
return object; | |
} | |
/* Change Properties values */ | |
export const changeFromToValues = (object, from, to) => { | |
for (const key in object) { | |
if (object[key] === from) { | |
object[key] = to; | |
} | |
} | |
return object; | |
} | |
/* Convert properties Number String to Number */ | |
export const stringToNumber = (object, properties) => { | |
properties.forEach(property => { | |
if (!isNaN(+object[property])) { | |
object[property] = +object[property]; | |
} | |
}); | |
return object; | |
} | |
/* Convert properties Boolean to Number */ | |
export const booleanToNumber = (object) => { | |
for (const key in object) { | |
if (typeof object[key] === "boolean") { | |
object[key] = object[key] === false ? 0 : 1; | |
} | |
} | |
return object; | |
}; | |
/* Character Count */ | |
export const characterCount = (str, char) => str.split(char).length - 1; | |
/* Check if Object is Empty */ | |
export const isObjectEmpty = (obj) => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object; | |
/* Check if array is not empty */ | |
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0; | |
isNotEmpty([1, 2, 3]); | |
// Result: true | |
/* Check if touchstart event is supported */ | |
export const touchsupported = () => ('ontouchstart' in window || DocumentTouch && document instanceof DocumentTouch); | |
/* Copy to Clipboard */ | |
export const copyToClipboard = (text) => navigator.clipboard.writeText(text); | |
copyToClipboard("Hello World"); | |
/* Check if Date is valid */ | |
export const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf()); | |
isDateValid("December 17, 1995 03:24:00"); | |
// Result: true | |
/* Find the day of year */ | |
export const dayOfYear = (date) => | |
Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24); | |
dayOfYear(new Date()); | |
// Result: 272 | |
/* Capitalise a string */ | |
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1) | |
console.log(capitalize("follow for more")); | |
// Result: Follow for more | |
/* Find number of days between two dates */ | |
export const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000) | |
dayDif(new Date("2020-10-21"), new Date("2021-10-22")) | |
// Result: 366 | |
/* Clear all cookies */ | |
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`)); | |
/* Generate random Hex color */ | |
export const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`; | |
console.log(randomHex()); | |
// Result: #92b008 | |
/* Remove duplicated from array */ | |
export const removeDuplicates = (arr) => [...new Set(arr)]; | |
console.log(removeDuplicates([1, 2, 3, 3, 4, 4, 5, 5, 6])); | |
// Result: [ 1, 2, 3, 4, 5, 6 ] | |
/* Get Query params from URL */ | |
export const getParameters = (URL) => { | |
URL = JSON.parse('{"' + decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}'); | |
return JSON.stringify(URL); | |
}; | |
getParameters(window.location) | |
// Result: { search : "easy", page : 3 } | |
/* Log time from date */ | |
const timeFromDate = date => date.toTimeString().slice(0, 8); | |
console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); | |
// Result: "17:30:00" | |
/* Check if number is Even or Odd */ | |
const isEven = num => num % 2 === 0; | |
console.log(isEven(2)); | |
// Result: True | |
/* Find the average of numbers */ | |
export const average = (...args) => args.reduce((a, b) => a + b) / args.length; | |
average(1, 2, 3, 4); | |
// Result: 2.5 | |
/* Reverse a string */ | |
const reverse = str => str.split('').reverse().join(''); | |
reverse('hello world'); | |
// Result: 'dlrow olleh' | |
/* Get selected text */ | |
export const getSelectedText = () => window.getSelection().toString(); | |
getSelectedText(); | |
/* Shuffle an array */ | |
export const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random()); | |
console.log(shuffleArray([1, 2, 3, 4])); | |
// Result: [ 1, 4, 3, 2 ] | |
/* Check if user device is in Dark mode */ | |
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches | |
console.log(isDarkMode) // Result: True or False | |
/* Convert RGB to HEX */ | |
export const rgbToHex = (r, g, b) => | |
"#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); | |
rgbToHex(0, 51, 255); | |
// Result: #0033ff | |
/* Compare 2 arrays */ | |
// `a` and `b` are arrays | |
export const areArraysEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b); | |
// Or | |
// export const areArraysEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]); | |
// Examples | |
areArraysEqual([1, 2, 3], [1, 2, 3]); // true | |
areArraysEqual([1, 2, 3], [1, '2', 3]); // false | |
/* Convert an array of objects to an object */ | |
export const toObject = (arr, key) => Object.fromEntries(arr.map((it) => [it[key], it])); | |
// Example | |
toObject([ | |
{ id: '1', name: 'Alpha', gender: 'Male' }, | |
{ id: '2', name: 'Bravo', gender: 'Male' }, | |
{ id: '3', name: 'Charlie', gender: 'Female' }], | |
'id'); | |
/* // Results | |
{ | |
'1': { id: '1', name: 'Alpha', gender: 'Male' }, | |
'2': { id: '2', name: 'Bravo', gender: 'Male' }, | |
'3': { id: '3', name: 'Charlie', gender: 'Female' } | |
} | |
*/ | |
/* Count by the properties of an array of objects */ | |
export const countBy = (arr, prop) => arr.reduce((prev, curr) => ((prev[curr[prop]] = ++prev[curr[prop]] || 1), prev), {}); | |
// Example | |
countBy([ | |
{ branch: 'audi', model: 'q8', year: '2019' }, | |
{ branch: 'audi', model: 'rs7', year: '2020' }, | |
{ branch: 'ford', model: 'mustang', year: '2019' }, | |
{ branch: 'ford', model: 'explorer', year: '2020' }, | |
{ branch: 'bmw', model: 'x7', year: '2020' }, | |
], | |
'branch'); | |
// { 'audi': 2, 'ford': 2, 'bmw': 1 } | |
/* Check if multiple objects are equal */ | |
export const areObjectsEqual = (...objects) => objects.every((obj) => JSON.stringify(obj) === JSON.stringify(objects[0])); | |
// Examples | |
areObjectsEqual({ foo: 'bar' }, { foo: 'bar' }); // true | |
areObjectsEqual({ foo: 'bar' }, { bar: 'foo' }); // false | |
/* Extract values of a property from an array of objects */ | |
export const pluck = (objs, property) => objs.map((obj) => obj[property]); | |
// Example | |
pluck([ | |
{ name: 'John', age: 20 }, | |
{ name: 'Smith', age: 25 }, | |
{ name: 'Peter', age: 30 }, | |
], | |
'name'); | |
// ['John', 'Smith', 'Peter'] | |
/* Invert keys and values of a object */ | |
export const invert = (obj) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [v, k])); | |
// Example | |
invert({ a: '1', b: '2', c: '3' }); // { 1: 'a', 2: 'b', 3: 'c' } | |
/* Remove all null and undefined from array */ | |
export const removeFalsy = (arr) => arr.filter(Boolean); | |
removeFalsy([1, 2, '3', undefined, { five: false }, null, 'seven', '']) // [1, 2, '3', { five: false }, 'seven'] | |
/* Remove all null and undefined from object */ | |
// export const removeNullUndefined = (obj) => | |
// Object.entries(obj) | |
// .reduce((a, [k, v]) => (v == null ? a : ((a[k] = v), a)), {}); | |
// Or | |
// export const removeNullUndefined = (obj) => | |
// Object.entries(obj) | |
// .filter(([_, v]) => v != null) | |
// .reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {}); | |
// Or | |
export const removeNullUndefined = (obj) => Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null)); | |
// Example | |
removeNullUndefined({ | |
foo: null, | |
bar: undefined, | |
fuzz: 42 | |
}); | |
// { fuzz: 42 } | |
/* Sort an object by its properties */ | |
export const sort = (obj) => | |
Object.keys(obj) | |
.sort() | |
.reduce((p, c) => ((p[c] = obj[c]), p), {}); | |
// Example | |
const colors = { | |
white: '#ffffff', | |
black: '#000000', | |
red: '#ff0000', | |
green: '#008000', | |
blue: '#0000ff', | |
}; | |
sort(colors); | |
/* | |
{ | |
black: '#000000', | |
blue: '#0000ff', | |
green: '#008000', | |
red: '#ff0000', | |
white: '#ffffff', | |
} | |
*/ | |
/* Check if an object is a promise */ | |
export const isPromise = (obj) => | |
!!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; | |
// or just resolve the Object! Like Promise.resolve(obj).then( ...do somehing here) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment