Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

VanillaJS便利関数ワンライナー

Last updated at Posted at 2024-04-07
utilityまとめ.js
const $$ = document;
const $ = v => v.startsWith('#') ? $$.getElementById(v.slice(1)) : $$.querySelector(v);
const _$ = (e = "div") => $$.createElement(e);
const DOM = str => new DOMParser().parseFromString(str, "text/html").body.firstElementChild;
const attr = (e, att) => Object.entries(att).map(([k, v]) => e[k] = v);
const css = (e, sty) => Object.entries(sty).map(([k, v]) => e.style[k] = v);
const event = (e, f, v = 'click') => e.addEventListener(v, f);
const sleep = (ms) => new Promise(r => setTimeout(r, ms));
const YYYYMMDD = new Date().toISOString().split("T")[0].replaceAll("-", "");
const rand = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
const uuid = () => crypto.randomUUID();
// yyyy-MM-DD HH:mm:ssで現在日時
const now = new Date();
const dt = now.getFullYear() + '-'
    + ('0' + (now.getMonth() + 1)).slice(-2) + '-'
    + ('0' + now.getDate()).slice(-2) + ' '
    + ('0' + now.getHours()).slice(-2) + ':'
    + ('0' + now.getMinutes()).slice(-2) + ':'
    + ('0' + now.getSeconds()).slice(-2);
linaria風css生成関数.js
/** linaria風 styleをクラス化する関数 */
const styleElement = document.createElement('style');
document.head.appendChild(styleElement);

/**
 * スタイルの表現文字列をクラスとして登録し、クラス名を生成する
 * @param {string} str スタイルを列挙した文字列
 * @returns {string} クラス名
 */
export const css = str => {
    const newClassNm = `css-${crypto.randomUUID()}`;
    const newClass = `.${newClassNm} {
        ${str}
    }`;
    styleElement.appendChild(document.createTextNode(newClass));
    return newClassNm;
};
DOMをいったん文字列扱いし連結できるようにする.js
/** DOM関連 */
export const DOM = {
    UUID_STORE: {},
    /**
     * HTML文字列からDOMオブジェクトを生成
     * @param {string} str HTML表現文字列
     * @returns {Element} 生成した要素
     */
    parse: str => new DOMParser().parseFromString(str, "text/html").body.firstElementChild,
    /**
     * イベント付きDOMオブジェクトを簡易化した文字列に変換
     * 簡易化したid付き要素のHTML表現文字列は、DOM.expand関数によってDOMオブジェクトに変換される
     * @param {Element} dom DOMオブジェクト
     * @returns {string[]} [id, dom] = [uuid, HTML表現文字列]
     */
    zip: dom => {
        const id = `id-${crypto.randomUUID()}`;
        DOM.UUID_STORE[id] = dom;
        return [id, `<div id="${id}"></div>`];
    },
    /**
     * DOMオブジェクト内部の簡易化された要素を展開する
     * @param {Element} dom DOMオブジェクト
     * @param {string[]} uuidlist 復元対象DOMオブジェクトのid配列
     * @returns {Element} 展開後のDOMオブジェクト
     */
    expand: (dom, uuidlist) => {
        for (const uuid of uuidlist) {
            dom.querySelector(`#${uuid}`)?.replaceWith(DOM.UUID_STORE[uuid]);
            delete DOM.UUID_STORE[uuid];
        }
        return dom;
    },
};
タイマー付き遅延関数.js
const sleep = (ms) => new Promise(r => setTimeout(r, ms));
const delay = async function(f, m) {
    for (i = 1; i <= m; ++i) {
        await sleep(6e4);
        console.log(`\u001b[36m${i}分\u001b[0m経過`);
    }
    console.log('=== \u001b[31m実行\u001b[0m ===');
    f();
};
delay(() => {
    // 処理を書く
}, 5); // 5分後に実行
ajaxまとめ.js
    const tokenKey = "sample-store-token";
    const ajax = {
        E: "https://xxxx.com/api",
        H: {"Content-Type": "application/json", "some-header": localStorage.getItem(tokenKey)},
        er: async er => {
            console.error(er);
            await fetch("https://serna37.github.io/util-js-api/msg").then(v => v.ok && v.text()).then(eval);
            utilJsApi.msg("fetch error", "error");
        },
        _: async (m, u, r) => await fetch(`${ajax.E}${u}`,
            r ? {headers: ajax.H} : {method: m, headers: ajax.H, body: JSON.stringify(r)})
            .then(v => v.ok ? v.json() : 0).catch(async e => {
                await ajax.er(e);
                return 0;
            }),
        get: async url => await ajax._("GET", url),
        post: async (url, req) => await ajax._("POST", url, req),
        patch: async (url, req) => await ajax._("PATCH", url, req),
        put: async (url, req) => await ajax._("PUT", url, req),
        delete: async (url, req) => await ajax._("DELETE", url, req),
    };
    /*
    // Usage
    const data = [
        {id: 1, name: "test"},
        {id: 2, name: "test"},
        {id: 3, name: "test"},
        {id: 4, name: "test"},
    ];
    const res = await ajax.patch(`/test`, data);
    if (res) console.log(res);
    // status.okがNGやcatch時はresがfalsy (0が返却)
    */
    // ================================
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?