Skip to content

Instantly share code, notes, and snippets.

@guyjin
Last active May 6, 2024 11:18
Show Gist options
  • Select an option

  • Save guyjin/d6a0800dff3616745baa90701f0fd809 to your computer and use it in GitHub Desktop.

Select an option

Save guyjin/d6a0800dff3616745baa90701f0fd809 to your computer and use it in GitHub Desktop.
JS One-liner collection
// `h` is an hour number between 0 and 23
const suffixAmPm = (h) => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? 'am' : 'pm'}`;// Examples
suffixAmPm(0); // '12am'
suffixAmPm(5); // '5am'
suffixAmPm(12); // '12pm'
suffixAmPm(15); // '3pm'
suffixAmPm(23); // '11pm'
const toObject = (arr, key) => arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {});// Or
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');/*
{
'1': { id: '1', name: 'Alpha', gender: 'Male' },
'2': { id: '2', name: 'Bravo', gender: 'Male' },
'3': { id: '3', name: 'Charlie', gender: 'Female' }
}
*/
history.back();// Or
history.go(-1);
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)
capitalize("follow for more")
// Result: Follow for more
const isNotEmpty = (arr) => Array.isArray(arr) && Object.keys(arr).length > 0;// Examples
isNotEmpty([]); // false
isNotEmpty([1, 2, 3]); // true
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
isDateValid("December 17, 1995 03:24:00");
// Result: true
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());isDateValid("December 17, 1995 03:24:00"); // true
const isArray = (obj) => Array.isArray(obj);
const isPromise = (obj) =>
!!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
const isTabInView = () => !document.hidden; // Not hidden
isTabInView();
// true/false
const isArray = (arr) => Array.isArray(arr);
console.log(isArray([1, 2, 3]));
// true
console.log(isArray({ name: 'Ovi' }));
// false
console.log(isArray('Hello World'));
// false
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
// `a` and `b` are arrays
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);// Or
const isEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);// Examples
isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [1, '2', 3]); // false
const isEqual = (...objects) => objects.every((obj) => JSON.stringify(obj) === JSON.stringify(objects[0]));// Examples
isEqual({ foo: 'bar' }, { foo: 'bar' }); // true
isEqual({ foo: 'bar' }, { bar: 'foo' }); // false
const getUrlParams = (query) =>Array.from(new URLSearchParams(query)).reduce((p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v }),{});// Examples
getUrlParams(location.search); // Get the parameters of the current URLgetUrlParams('foo=Foo&bar=Bar'); // { foo: "Foo", bar: "Bar" }// Duplicate key
getUrlParams('foo=Foo&foo=Fuzz&bar=Bar'); // { foo: ["Foo", "Fuzz"], bar: "Bar" }
const cookies = document.cookie.split(';').map((item) => item.split('=')).reduce((acc, [k, v]) => (acc[k.trim().replace('"', '')] = v) && acc, {});
const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");
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
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
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
console.log(isDarkMode) // Result: True or False
const hasFocus = (ele) => ele === document.activeElement;
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// Result: 2.5
const dayOfYear = (date) =>
Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date());
// Result: 272
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
console.log(randomHex());
// Result: #92b008
const randomString = () => Math.random().toString(36).slice(2);
console.log(randomString());
// could be anything!!!
const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
cookie('_ga');
// Result: "GA1.2.1929736587.1601974046"
const siblings = (ele) => [].slice.call(ele.parentNode.children).filter((child) => child !== ele);
const trueTypeOf = (obj) => {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
};
console.log(trueTypeOf(''));
// string
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf());
// undefined
console.log(trueTypeOf(null));
// null
console.log(trueTypeOf({}));
// object
console.log(trueTypeOf([]));
// array
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf(() => {}));
// function
const getSelectedText = () => window.getSelection().toString();
getSelectedText();
const uniqueArr = (arr) => [...new Set(arr)];
console.log(uniqueArr([1, 2, 3, 1, 2, 3, 4, 5]));
// [1, 2, 3, 4, 5]
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']
const invert = (obj) => Object.keys(obj).reduce((res, k) => Object.assign(res, { [obj[k]]: k }), {});// Or
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' }
const isWeekend = (date) => [0, 6].indexOf(date.getDay()) !== -1;
console.log(isWeekend(new Date(2021, 4, 14)));
// false (Friday)
console.log(isWeekend(new Date(2021, 4, 15)));
// true (Saturday)
const isRelative = (path) => !/^([a-z]+:)?[\\/]/i.test(path);// Examples
isRelative('/foo/bar/baz'); // false
isRelative('C:\\foo\\bar\\baz'); // false
isRelative('foo/bar/baz.txt'); // true
isRelative('foo.md'); // true
const isBrowser = typeof window === 'object' && typeof document === 'object';
const isNode = typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
const isHexColor = (color) => /^#([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i.test(color);// Examples
isHexColor('#012'); // true
isHexColor('#A1B2C3'); // true
isHexColor('012'); // false
isHexColor('#GHIJKL'); // false
just a collection of js one-liners from around the web.
const timeFromDate = date => date.toTimeString().slice(0, 8);
console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0)));
// Result: "17:30:00"
// Merge but don't remove the duplications
const merge = (a, b) => a.concat(b);
// Or
const merge = (a, b) => [...a, ...b];
// Merge and remove the duplications
const merge = [...new Set(a.concat(b))];
// Or
const merge = [...new Set([...a, ...b])];
// There are a couple of ways to merge arrays. One of them is using the "concat" method. Another one is using the spread operator ("…").
// PS: We can also any duplicates from the final array using the "Set" object.
const isEven = num => num % 2 === 0;
console.log(isEven(2));
// Result: True
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 }
const getRandomBoolean = () => Math.random() >= 0.5;
console.log(getRandomBoolean());
// a 50/50 chance of returning true or false
const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;// Or
const randomColor = () => `#${(~~(Math.random() * (1 << 24))).toString(16)}`;
const randomIp = () => Array(4).fill(0)
.map((_, i) => Math.floor(Math.random() * 255) + (i === 0 ? 1 : 0))
.join('.');// Example
randomIp(); // 175.89.174.131
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
console.log(random(1, 50));
// could be anything from 1 - 50
const randomStr = () => require('crypto').randomBytes(32).toString('hex');
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 ]
const removeNullUndefined = (obj) =>
Object.entries(obj)
.reduce((a, [k, v]) => (v == null ? a : ((a[k] = v), a)), {});// Or
const removeNullUndefined = (obj) =>
Object.entries(obj)
.filter(([_, v]) => v != null)
.reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {});// Or
const removeNullUndefined = (obj) => Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));// Example
removeNullUndefined({
foo: null,
bar: undefined,
fuzz: 42});
// { fuzz: 42 }
const repeat = (str, numberOfTimes) => str.repeat(numberOfTimes);
const reverse = str => str.split('').reverse().join('');
reverse('hello world');
// Result: 'dlrow olleh'
const rgbToHex = (r, g, b) =>
"#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
rgbToHex(0, 51, 255);
// Result: #0033ff
const goToTop = () => window.scrollTo(0, 0);
goToTop();
const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());
console.log(shuffleArray([1, 2, 3, 4]));
// Result: [ 1, 4, 3, 2 ]
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',
}
*/
[foo, bar] = [bar, foo];
// Longhand
const age = 18;
let greetings;
if (age < 18) {
greetings = 'You are not old enough';
} else {
greetings = 'You are young!';
}
// Shorthand
const greetings = age < 18 ? 'You are not old enough' : 'You are young!';
// bool is stored somewhere in the upperscope
const toggleBool = () => (bool = !bool);
const truncateString = (string, length) => {
return string.length < length ? string : `${string.slice(0, length - 3)}...`;
};
console.log(
truncateString('Hi, I should be truncated because I am too loooong!', 36),
);
// Hi, I should be truncated because...
const truncateStringMiddle = (string, length, start, end) => {
return `${string.slice(0, start)}...${string.slice(string.length - end)}`;
};
console.log(
truncateStringMiddle(
'A long story goes here but then eventually ends!', // string
25, // total size needed
13, // chars to keep from start
17, // chars to keep from end
),
);
// A long story ... eventually ends!
const lowercaseFirst = (str) => `${str.charAt(0).toLowerCase()}${str.slice(1)}`;// Example
lowercaseFirst('Hello World'); // 'hello World'
// Longhand
if (name !== null || name !== undefined || name !== '') {
let fullName = name;
}
// Shorthand
const fullName = name || 'buddy';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment