UNPKG

@techmely/utils

Version:

Collection of helpful JavaScript / TypeScript utils

68 lines (61 loc) 1.67 kB
'use strict'; /*! * @techmely/utils * Copyright(c) 2021-2024 Techmely <techmely.creation@gmail.com> * MIT Licensed */ // src/invariant.ts var prefix = "Invariant failed"; function invariant(condition, message) { if (condition) { return; } if (typeof message === "string" || typeof message === "function") { const provided = typeof message === "function" ? message() : message; const value = provided ? `${prefix}: ${provided}` : prefix; throw new Error(value); } if (message) throw message; throw new Error(prefix); } // src/isBrowser.ts function isBrowser() { return typeof window !== "undefined"; } // src/createElement/createElement.ts function createElement(tag, ...children) { invariant(isBrowser(), "Not in browser environment"); let element = tag; if (typeof element === "string") element = document.createElement(element); let i = 1; const next = arguments[1]; if (next && typeof next === "object" && !next.nodeType && !Array.isArray(next)) { for (const name in next) { const value = next?.[name]; if (typeof value === "string") element.setAttribute(name, value); if (value) element[name] = value; } i++; } for (; i < arguments.length; i++) add(element, arguments[i]); return element; } function add(element, child) { if (!child) return; if (typeof child === "string") { element.appendChild(document.createTextNode(child)); } else if (child.nodeType !== null) { element.appendChild(child); } else if (Array.isArray(child)) { for (const c of child) { add(element, c); } } } exports.createElement = createElement;