Passed
Push — main ( 67f6a3...fa9d82 )
by Andrii
02:11
created

core.ts ➔ joinWithLead   A

Complexity

Conditions 3

Size

Total Lines 12
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 12
rs 9.85
c 0
b 0
f 0
cc 3
1
import { EMPTY_ARRAY } from "./consts"
2
import type { ClassValue, Falsy } from "./defs"
3
4
const {keys: $keys} = Object
5
6
export {
7
  truthyKeys,
8
  dehash,
9
  joinWithLead
10
}
11
12
function dehash<K extends string>(source: Record<K, unknown>, keys: string[] = $keys(source)) :string[] {
13
  for (let i = keys.length; i--;) {
14
    const key = keys[i] as K
15
    , value = source[key]
16
17
    if (typeof value === "string")
18
      keys[i] = value
19
  }
20
21
  return keys
22
}
23
24
//TODO TS is not working interesting
25
function truthyKeys<T>(source: Falsy) :T[];
26
function truthyKeys<T extends Record<string, unknown>>(source: Readonly<T>): (
27
  {[K in keyof typeof source]: typeof source[K] extends Falsy ? never : K}[keyof typeof source]
28
)[];
29
function truthyKeys<T>(source: T): [T];
30
function truthyKeys<T>(source: T) {
31
  if (source === null || typeof source !== "object")
32
    return source
33
    ? [source]
34
    : EMPTY_ARRAY
35
    
36
  const filtered = (
37
    $keys(source) as (keyof T)[]
38
  )
39
  //TODO consider `delete` and further `flat` in case of perf
40
  .filter(key => source[key])
41
42
  return filtered
43
}
44
45
//TODO Consider undefined
46
function joinWithLead(value: Falsy|ClassValue, arr: readonly string[]) :string {
47
  const str1 = value || ""
48
  if (!arr.length)
49
    return str1
50
  
51
  const str2  = arr.join(" ")
52
  if (!str1)
53
    return str2
54
55
  return `${str1} ${str2}`
56
}