From d48cafebb277e4ad4b31e883cbe4f55eef9ea4a4 Mon Sep 17 00:00:00 2001 From: Joris Date: Sat, 29 May 2021 19:24:41 +0200 Subject: Rewrite in TypeScript --- src/lib/dom.ts | 6 ++++++ src/lib/format.ts | 9 +++++++++ src/lib/function.ts | 7 +++++++ src/lib/h.ts | 30 ++++++++++++++++++++++++++++++ src/lib/search.ts | 11 +++++++++++ 5 files changed, 63 insertions(+) create mode 100644 src/lib/dom.ts create mode 100644 src/lib/format.ts create mode 100644 src/lib/function.ts create mode 100644 src/lib/h.ts create mode 100644 src/lib/search.ts (limited to 'src/lib') diff --git a/src/lib/dom.ts b/src/lib/dom.ts new file mode 100644 index 0000000..2ab4de5 --- /dev/null +++ b/src/lib/dom.ts @@ -0,0 +1,6 @@ +export function replaceChildren(parent: Element, ...newChildren: Element[]) { + while (parent.lastChild) { + parent.removeChild(parent.lastChild) + } + newChildren.forEach(c => parent.appendChild(c)) +} diff --git a/src/lib/format.ts b/src/lib/format.ts new file mode 100644 index 0000000..28aa50f --- /dev/null +++ b/src/lib/format.ts @@ -0,0 +1,9 @@ +export function decimal(n: number): string { + const str = n.toString() + const xs = str.split('.') + if (xs.length == 2) { + return `${xs[0]},${xs[1].slice(0, 2).padEnd(2, '0')}` + } else { + return `${str},00` + } +} diff --git a/src/lib/function.ts b/src/lib/function.ts new file mode 100644 index 0000000..db7b436 --- /dev/null +++ b/src/lib/function.ts @@ -0,0 +1,7 @@ +export function debounce(func: any, timeout = 300){ + let timer: any; + return (...args: any) => { + clearTimeout(timer); + timer = setTimeout(() => { func.apply(this, args); }, timeout); + }; +} diff --git a/src/lib/h.ts b/src/lib/h.ts new file mode 100644 index 0000000..bb21efd --- /dev/null +++ b/src/lib/h.ts @@ -0,0 +1,30 @@ +type Child = Element | Text | string | number + +export default function h( + tagName: string, + attrs: object, + ...children: Child[] +): Element { + const isSvg = tagName === 'svg' || tagName === 'path' + + let elem = isSvg + ? document.createElementNS('http://www.w3.org/2000/svg', tagName) + : document.createElement(tagName) + + if (isSvg) { + Object.entries(attrs).forEach(([key, value]) => { + elem.setAttribute(key, value) + }) + } else { + elem = Object.assign(elem, attrs) + } + + for (const child of children) { + if (typeof child === 'number') + elem.append(child.toString()) + else + elem.append(child) + } + + return elem +} diff --git a/src/lib/search.ts b/src/lib/search.ts new file mode 100644 index 0000000..7b9530e --- /dev/null +++ b/src/lib/search.ts @@ -0,0 +1,11 @@ +export function match(search: string, target: string): boolean { + return search.split(/\s+/).every(s => format(target).includes(format(s))) +} + +export function format(str: string): string { + return unaccent(str.toLowerCase()) +} + +function unaccent(str: string): string { + return str.normalize("NFD").replace(/[\u0300-\u036f]/g, "") +} -- cgit v1.2.3