1
|
|
|
import { EMPTY_ARRAY } from "./consts" |
2
|
|
|
import type { ClassNamed, ClassValue, Falsy } from "./defs" |
3
|
|
|
import { stringifyClassNamed } from "./utils" |
4
|
|
|
|
5
|
|
|
const classNameKey = "className" as const |
6
|
|
|
|
7
|
|
|
const {keys: $keys} = Object |
8
|
|
|
|
9
|
|
|
export { |
10
|
|
|
wrapper, |
11
|
|
|
truthyKeys, |
12
|
|
|
dehash, |
13
|
|
|
joinWithLead |
14
|
|
|
} |
15
|
|
|
|
16
|
|
|
function wrapper<T>( |
17
|
|
|
destination: T, |
18
|
|
|
className: undefined | string |
19
|
|
|
) { |
20
|
|
|
//@ts-expect-error |
21
|
|
|
destination[classNameKey] = className |
22
|
|
|
|
23
|
|
|
return stringifyClassNamed(destination as T & ClassNamed) |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
function dehash<K extends string>(source: Record<K, unknown>, keys: string[] = $keys(source)) :string[] { |
27
|
|
|
for (let i = keys.length; i--;) { |
28
|
|
|
const key = keys[i] as K |
29
|
|
|
, value = source[key] |
30
|
|
|
|
31
|
|
|
if (typeof value === "string") |
32
|
|
|
keys[i] = value |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
return keys |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
//TODO TS is not working interesting |
39
|
|
|
function truthyKeys<T>(source: Falsy) :T[]; |
40
|
|
|
function truthyKeys<T extends Record<string, unknown>>(source: Readonly<T>): ( |
41
|
|
|
{[K in keyof typeof source]: typeof source[K] extends Falsy ? never : K}[keyof typeof source] |
42
|
|
|
)[]; |
43
|
|
|
function truthyKeys<T>(source: T): [T]; |
44
|
|
|
function truthyKeys<T>(source: T) { |
45
|
|
|
if (source === null || typeof source !== "object") |
46
|
|
|
return source |
47
|
|
|
? [source] |
48
|
|
|
: EMPTY_ARRAY |
49
|
|
|
|
50
|
|
|
const filtered = ( |
51
|
|
|
$keys(source) as (keyof T)[] |
52
|
|
|
) |
53
|
|
|
//TODO consider `delete` and further `flat` in case of perf |
54
|
|
|
.filter(key => source[key]) |
55
|
|
|
|
56
|
|
|
return filtered |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
//TODO Consider returning `undefined` on empty string |
60
|
|
|
function joinWithLead(value: Falsy|ClassValue, arr: undefined | string | readonly string[]) : string { |
61
|
|
|
const str1 = value || "" |
62
|
|
|
if (!(arr && arr.length)) |
63
|
|
|
return str1 |
64
|
|
|
|
65
|
|
|
const str2 = typeof arr === "string" ? arr : arr.join(" ") |
66
|
|
|
if (!str1) |
67
|
|
|
return str2 |
68
|
|
|
|
69
|
|
|
return `${str1} ${str2}` |
70
|
|
|
} |