Skip to content

Instantly share code, notes, and snippets.

const machine = {
empty: {
SELECT: {
to: 'loading',
action: (state, dispatch) => {
interval.stop()
loadBook().then((book) => dispatch('SELECT_SUCCESS', book))
return { ...state, title: null, progress: 0 }
},
},
@Ivannnnn
Ivannnnn / usePrevious.js
Last active October 31, 2021 14:09
Hooks
function usePrevious(value) {
const ref = useRef()
useEffect(() => {
ref.current = value
}, [value])
return ref.current
}
const blockOne = (funcName) => {
if (funcName === 'one') {
return false
}
}
const emitEvent = (funcName) => {
console.log('[event] ' + funcName)
}
const store = {
actions: {
play: (dispatch, payload, actions) => {
// do some action
// payload --> 'abc'
dispatch('play', 'arg1', 'arg2')
}
},
reducer: {
play: (_) => ({ ..._ })
const audioPlayer = (function () {
const [state, updateState, watchState] = useState({
name: 'Ivan',
})
watchState({
name: (name) => {
console.log('name updated to: ' + name)
},
})
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)))
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(' ')
})
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
}
function keyBy(collection, key) {
const result = {}
collection.forEach(item => result[item[key]] = item)
return result
}
@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)
}