Passed
Push — master ( 1a93c4...2b2dc1 )
by Andrii
02:47
created

utils.ts ➔ extractDefaults   A

Complexity

Conditions 2

Size

Total Lines 13
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 13
c 0
b 0
f 0
rs 9.8
cc 2
1
import {readFileSync, unlink, exists} from "fs"
2
import {promisify} from "util"
3
import type { SchemaWithDefaultsAndExamples, DefaultsAndExamplesFromSchema } from "./ts-swiss.types"
4
5
const {keys: $keys} = Object
6
, $exists = promisify(exists)
7
, _unlink = promisify(unlink)
8
9
export {
10
  regexpize,
11
  extractDefaults,
12
  readlineSync,
13
  $exists,
14
  $unlink
15
}
16
17
function regexpize(source: string|RegExp, flags = "") {
18
  return typeof source === "string"
19
  ? new RegExp(source, flags)
20
  : source
21
}
22
23
function extractDefaults<S extends SchemaWithDefaultsAndExamples>({properties}: S) {
24
  const keys: Array<keyof typeof properties> = $keys(properties)
25
  , {length} = keys
26
  , defaults: Partial<DefaultsAndExamplesFromSchema<S>> = {}
27
28
  for (let i = length; i--; ) {
29
    const key = keys[i]
30
    //@ts-ignore
31
    defaults[key] = properties[key].default
32
  }
33
34
  return defaults as DefaultsAndExamplesFromSchema<S>
35
}
36
37
//TODO replace with common
38
function readlineSync(path: string, splitter: string) {
39
  return readFileSync(path).toString().split(splitter)
40
}
41
42
function $unlink(source: Parameters<typeof _unlink>[0]) {
43
  return $exists(source)
44
  .then(ex => ex ? _unlink(source) : void 0)
45
}
46