Snippets
Created by
Andrew Alba
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 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 | // Get Random Boolean
const getRandomBoolean = () => Math.random() >= 0.5;
console.log(getRandomBoolean());
// a 50/50 chance of returning true or false
// Check if the date is Weekend
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)
// Check if a number is even or odd
const isEven = (num) => num % 2 === 0;
console.log(isEven(5));
// false
console.log(isEven(4));
// true
// Get the unique values in an array
const uniqueArr = (arr) => [...new Set(arr)];
console.log(uniqueArr([1, 2, 3, 1, 2, 3, 4, 5]));
// [1, 2, 3, 4, 5]
// Check if a variable is an array
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
// Generate a random number between two numbers
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
console.log(random(1, 50));
// could be anything from 1 - 50
// Generate a random string (unique id?)
const randomString = () => Math.random().toString(36).slice(2);
console.log(randomString());
// could be anything!!!
// Scroll to the top of the page
const scrollToTop = () => window.scrollTo(0, 0);
scrollToTop();
// Toggle boolean
// bool is stored somewhere in the upperscope
const toggleBool = () => (bool = !bool);
// Calculate number of days between two dates
const daysDiff = (date, date2) => Math.ceil(Math.abs(date - date2) / 86400000);
console.log(daysDiff(new Date('2021-05-10'), new Date('2021-11-25')));
// 199
// Copy text to clipboard
const copyTextToClipboard = async (text) => {
await navigator.clipboard.writeText(text);
};
// 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])];
// Get the actual type of javascript primitives
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
// Truncate string at the end
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...
// Truncate string from the middle
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!
// Capitalizing a string
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
console.log(capitalize('hello world'));
// Hello world
// Check if the current tab is in view/focus
const isTabInView = () => !document.hidden; // Not hidden
isTabInView();
// true/false
// Check if the user is on an Apple device
const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
// true/false
// The Ternary Operator
// 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!';
// Short-circuit Evaluation Shorthand
// Longhand
if (name !== null || name !== undefined || name !== '') {
let fullName = name;
}
// Shorthand
const fullName = name || 'buddy';
|
Comments (0)
You can clone a snippet to your computer for local editing. Learn more.