A collection of JS Oneliners

ES6 oneliners are awesome.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
// Get random boolean
const randomBoolean = () => Math.random() >= 0.5;

// Check if the provided day is a weekday or a weekend-day
const isWeekday = (date) => date.getDay() % 6!=0;
// console.log(isWeekday (new Date(2021,0,11)));

// reverse a string
const reverse = str => str.split('').reverse().join('');

// check if the current tab is in view/focus
const checkTabFocus = () => document.hidden

// check if a number is even or odd
const isEven = num => num % 2 === 0;

const getTime = date => date.toTimeString(),slice(0,8);
console.log(getTime(new Date(2021,0,10,16,30,0))); // use .toTimeString() method to slice the string.
console.log(getTime(new Date()));

//Truncate number to a fixed decimal point
const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
// Examples
// toFixed(25.198726354, 1);       // 25.1
// toFixed(25.198726354, 2);       // 25.19
// toFixed(25.198726354, 3);       // 25.198

const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// Result: 2.5

const touchSupported = () => {
  ('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}
console.log(touchSupported());
// Result: will return true if touch events are supported, false if not

// Generate unique ID
const ID = (prefix="_") => (prefix + Math.random().toString(36).substr(2, 9));
console.log(ID("x")); // returns: xlafwd4hws

// Capitalize the first letter of a string
const capitalize = str => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;

// Calculate the number of days between two dates
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
diffDays(new Date('2014-12-19'), new Date('2020-01-01'));
// Result: 1839

// Convert a string to a number implicitly
toNumber = str => +str;
// Convert a string to a number explicitly
toNumber = str => Number(str);
toNumber("3412");
// Result: 2

// Check if an array contains any items
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]);
// Result: true
isNotEmpty([]);
// Result: false

// Different ways of merging multiple arrays
// 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])];

// Sort an array containing numbers
const sort = arr => arr.sort((a, b) => a - b);
sort([1, 5, 2, 4, 3]);
// Result: [1, 2, 3, 4, 5]

// Generate a random HEX color
randomColor = () => `#${Math.random().toString(16).slice(2, 8).padStart(6, '0')}`;
// Or
const randomColor = () => `#${(~~(Math.random()*(1<<24))).toString(16)}`;

// Swap the values of 2 variables
let a = 1;
let b = 2;
[a, b] = [b, a];
// Result: 
// a = 2
// b = 1

// Get the text that the user has selected
const getSelectedText = () => window.getSelection().toString();
getSelectedText();

let array = [0, 1, 2, 3 ,4 , 5 , 6 , 7 , 8 , 9];
console.log(array.slice(-1)); // Result: [9]
console.log(array.slice(-2)); // Result: [8, 9]
console.log(array.slice(-3)); // Result: [7, 8, 9]

const dynamic = "model";
const item = {
  brand: "Porsche",
  [dynamic]: "Panamera"
}
console.log(item);
// { brand: "Porsche", model: "Panamera" }

// Improve custom cursor performance by using “translate3d”
// Slow :(
customCursor.style.top = "100px"; 
customCursor.style.left = "50px";
// Better! :D 
customCursor.style.transform = translate3d(${xPosition}, ${yPosition}, 0);

// NodeList to Array:
var headings = [ ... document.querySelectorAll('h1') ];

// Unique Arrays:
[ ...new Set(array) ] 

// Destructuring:
var {foo, bar} = {foo: "lorem", bar: "ipsum"};
// foo => lorem and bar => ipsum

// Swap like a snake:
[a,b] = [b,a]

// Max in array?:
Math.max(...array);

// List comprehension:
[ for (value of ["Harriet", "178"]) value ].join(" was ");
// Would give us "Harriet was 178"
// BTW it was Charles Darwin's tortoise.

// _map?
[{id: 1}, {id: 2}].map(x => x.id)
// [1,2]

// Object.isz!
let Object.isz = (x, y) => x === y || Object.is(x, y);

// Is it a hidden file?:
isHidden = (file) => /^\.|~$/.test(file);
isHidden(".DS_STORE") // true

// Repeat with me:
(0/0+"").repeat("7")+ " BatMan!"
// "NaNNaNNaNNaNNaNNaNNaN BatMan!"

// remove falsey values from arrays, like null and undefined
array.filter(Boolean); 

// sum of array of numbers
array.reduce((sum, num) => sum + num, 0); 

// Object.values polyfill
Object.values = (obj) => Object.keys(obj).map(key => obj[key]); 

// Sleep an async function for a second
await new Promise(r => setTimeout(r, 1000)); 

 // Wait for up to a second for work to be done
await Promise.race([doWork(), new Promise(r => setTimeout(r, 1000))]);

// Bonus: (not a one liner, but great for testing async in the console)
(async () => { await doWork(); await moreWork(); })().then(console.log, console.error);