Bookmarked JS
Parents' z-indexes
this example is designed to be run in DevTools console
let element = $0;
do {
const styles = window.getComputedStyle(element);
console.log(styles.zIndex, element);
} while (element.parentElement && (element = element.parentElement));
Copy to Clipboard
navigator.clipboard.writeText('foo bar')
Time Performance
function comparePerformance() {
let timeStart = performance.now();
for (let i = 0; i < 1000000; i++) {
f1();
}
console.log(`f1 time is ${performance.now() - timeStart}`);
timeStart = performance.now();
for (let i = 0; i < 1000000; i++) {
f2();
}
console.log(`f2 time is ${performance.now() - timeStart}`);
}
Caching
function cacheFunctionResult(callback) {
let prevArgs = [];
let prevValue = null;
return (...args) => {
if (args.every((arg, i) => arg === prevArgs[i])) {
return prevValue;
}
prevArgs = args;
prevValue = callback(...args);
return prevValue;
};
}
Debounce
debounce is used to avoid repetitive calls of a function per unit of time. each new call of debounced function cancels the previous one and restarts timer
function debounce(f, delay) {
let timerId = 0;
return (...args) => {
clearTimeout(timerId);
timerId = setTimeout(f, delay, ...args);
};
}
Throttle
throttle is used to limit amount of function calls to one per unit of time
function throttle(f, delay) {
let isBusy = false;
let savedArgs = null;
return function wrapper(...args) {
if (isBusy) {
savedArgs = args;
return;
}
isBusy = true;
savedArgs = null;
f(...args);
setTimeout(() => {
isBusy = false;
if (savedArgs) {
wrapper(...savedArgs);
}
}, delay);
};
}
IDs for Unique Objects
this code generates unique IDs for objects based on their references: objects with same references get same ID
const ids = new WeakMap();
let currentId = 1;
function generateObjectId(object) {
if (ids.has(object)) {
return ids.get(object);
}
const id = String(currentId++);
ids.set(object, id);
return id;
}
Binary Search
function searchBinary(array, x) {
let left = 0;
let right = array.length - 1;
while (left <= right) {
let middle = Math.floor((left + right) / 2);
if (array[middle] === x) {
return middle;
}
if (array[middle] < target) {
left = middle + 1;
} else {
right = middle - 1;
}
}
return -1;
}
Linked List
class LinkedList {
constructor() {
this.head = null;
}
insertNew(data) {
let newNode = {
data,
next: null,
};
if (this.head === null) {
this.head = newNode;
} else {
let tail = this.head;
while (tail.next !== null) {
tail = tail.next;
}
tail.next = newNode;
}
}
}