Last active
December 9, 2022 20:52
-
-
Save jairusjoer/1752d4544a06c4eb6183d57f995cceba to your computer and use it in GitHub Desktop.
A collection of frequently used JavaScript snippets
This file contains 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
// Transform a ISO 8601 format date string to a given locale ―――――――――――――――― // | |
const date = (input, locale = "de-DE", options = { dateStyle: "long" }) => { | |
const date = Date.parse(input); | |
return new Intl.DateTimeFormat(locale, options).format(date); | |
}; | |
// Mount, toggle and store dark mode theme on client ―――――――――――――――――――――――― // | |
/** | |
* @param {object} night Configure night mode controls and targets. | |
* @param {string} night.mount Mount theme class to single given DOM element. | |
* @param {string} night.targets Match control targets using `querySelectorAll()`. | |
* @param {string} [night.theme] Set optional theme name to be mounted. Default: night. | |
* @param {function} [night.callback] Optional callback triggered on target interaction. | |
* @return {object} Current theme state and targeted DOM elements. | |
*/ | |
const night = ({ mount, targets, theme = "night", callback }) => { | |
const _data = { mount, targets }; | |
const _mount = document.querySelector(mount); | |
const _targets = document.querySelectorAll(targets); | |
if (localStorage.theme == theme) { | |
_mount.classList.add(theme); | |
callback({ ..._data, theme: localStorage.theme }); | |
} | |
_targets.forEach((item) => { | |
item.onclick = () => { | |
_mount.classList.toggle(theme); | |
localStorage.theme = localStorage.theme == theme ? "default" : theme; | |
callback({ ..._data, theme: localStorage.theme }); | |
return { ..._data, theme: localStorage.theme }; | |
}; | |
}); | |
}; | |
// Send JSON data as POST to specified url ―――――――――――――――――――――――――――――――――― // | |
const post = async (url, data) => { | |
const response = await fetch(url, { | |
method: "POST", | |
headers: { | |
"Content-Type": "application/json", | |
}, | |
body: JSON.stringify(data), | |
}); | |
return await response.json(); | |
}; | |
// Asynchronous sleep function ―――――――――――――――――――――――――――――――――――――――――――――― // | |
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); | |
export { date, night, post, sleep }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment