Skip to content

Instantly share code, notes, and snippets.

@Ivannnnn
Ivannnnn / onLocationChange.js
Created October 10, 2019 09:01
Subscribe to url change
const onLocationChange = (() => {
const subscribers = []
const fireEvent = () => subscribers.forEach(sub => sub())
const { pushState, replaceState } = window.history
window.history.pushState = function(...args) {
pushState.apply(window.history, args)
fireEvent()
}
const createEventBus = () => {
const subscribers = {}
let counter = 0
const on = (name, cb) => {
if (!subscribers[name]) subscribers[name] = {}
subscribers[name][++counter] = cb
return btoa(name + '.' + counter)
}
const randomBetween = (min, max) =>
Math.floor(Math.random() * (max - min + 1) + min)
const $ = (q, container = document) => [...container.querySelectorAll(q)];
$.createFragment = Range.prototype.createContextualFragment.bind(
document.createRange()
);
$.attr = (el, attrs) => {
for (let prop in attrs) {
HTMLElement.prototype.hasOwnProperty(prop)
? (el[prop] = attrs[prop])
@Ivannnnn
Ivannnnn / observe.js
Last active January 4, 2020 17:08
Observes changes to an element until false is returned from the callback
const observe = (el, cb, options = { childList: true }) => {
const func = mutations => cb(mutations) === false && mo.disconnect()
const mo = new MutationObserver(func)
mo.observe(el, options)
}
function keyBy(collection, key) {
const result = {}
collection.forEach(item => result[item[key]] = item)
return result
}
export const newDate = (date, updates) => {
date = new Date(date)
Object.keys(updates).forEach((method) => {
const methodName = 'set' + method.replace(/^\w/, (c) => c.toUpperCase())
if (!date[methodName]) throw new Error(`Key '${method}' is not supported!`)
date[methodName](updates[method])
})
return date
}
export const classes = (...args) => {
return args
.map((arg) => {
if (arg === null || arg === undefined) return null
return typeof arg === 'string'
? arg
: Object.keys(arg)
.filter((key) => arg[key])
.join(' ')
})
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array)
}
}
const asyncMap = async (arr, cb) =>
Promise.all(arr.map(async (a, i) => await cb(a, i)))
const audioPlayer = (function () {
const [state, updateState, watchState] = useState({
name: 'Ivan',
})
watchState({
name: (name) => {
console.log('name updated to: ' + name)
},
})