Created
March 17, 2023 08:35
-
-
Save AnandPilania/f62d1aa3151d32d705b1b7c8c1938c61 to your computer and use it in GitHub Desktop.
JS helper utils
This file contains hidden or 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
function benchmark(times, callbacks) { | |
let result = {} | |
Object.entries(callbacks).forEach(([key, value]) => { | |
let thing = {} | |
let start = performance.now() | |
for (let index = 0; index < times; index++) { | |
value() | |
} | |
let end = performance.now() - start | |
result[key] = { | |
time: end, | |
} | |
}) | |
console.table(result) | |
} | |
function once(callback, fallback = () => {}) { | |
let called = false | |
return function () { | |
if (! called) { | |
called = true | |
callback.apply(this, arguments) | |
} else { | |
fallback.apply(this, arguments) | |
} | |
} | |
} | |
function walk(el, callback) { | |
if (el instanceof ShadowRoot) { | |
Array.from(el.children).forEach(el => walk(el, callback)) | |
return | |
} | |
let skip = false | |
callback(el, () => skip = true) | |
if (skip) return | |
let node = el.firstElementChild | |
while (node) { | |
walk(node, callback, false) | |
node = node.nextElementSibling | |
} | |
} | |
function get(obj, path) { | |
return path.split('.').reduce((carry, segment) => carry[segment], obj) | |
} | |
function set(obj, path, value) { | |
if (path.length === 1) obj[path[0]] = value; | |
else if (path.length === 0) throw error; | |
else { | |
if (obj[path[0]]) | |
return set(obj[path[0]], path.slice(1), value); | |
else { | |
obj[path[0]] = {}; | |
return set(obj[path[0]], path.slice(1), value); | |
} | |
} | |
} | |
function debounce(func, wait, immediate) { | |
var timeout | |
return function () { | |
var context = this, | |
args = arguments | |
var later = function () { | |
timeout = null | |
if (!immediate) func.apply(context, args) | |
} | |
var callNow = immediate && !timeout | |
clearTimeout(timeout) | |
timeout = setTimeout(later, wait) | |
if (callNow) func.apply(context, args) | |
} | |
} | |
function tap(output, callback) { | |
callback(output) | |
return output | |
} | |
function dispatch(el, name, detail = {}) { | |
el.dispatchEvent( | |
new CustomEvent(name, { | |
detail, | |
bubbles: true, | |
composed: true, | |
cancelable: true, | |
}) | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment