Skip to content

Instantly share code, notes, and snippets.

@calebporzio
Last active January 14, 2022 08:54
Show Gist options
  • Save calebporzio/22eb52b35a8fad1cc6006554f998979a to your computer and use it in GitHub Desktop.
Save calebporzio/22eb52b35a8fad1cc6006554f998979a to your computer and use it in GitHub Desktop.
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,
// Allows events to pass the shadow DOM barrier.
composed: true,
cancelable: true,
})
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment