Passed
Push — master ( 695a88...75a95e )
by Andrii
02:59
created

rewrite.ts ➔ rewrite   C

Complexity

Conditions 10

Size

Total Lines 46
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 39
dl 0
loc 46
rs 5.9999
c 0
b 0
f 0
cc 10

How to fix   Complexity   

Complexity

Complex classes like rewrite.ts ➔ rewrite often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
import {promisify} from "util"
2
import {createReadStream, open, writeFile, close } from 'fs'
3
import {createInterface} from 'readline'
4
import { $exists } from "./utils"
5
6
const $open = promisify(open)
7
, $write = promisify(writeFile)
8
, $close = promisify(close)
9
10
export = rewrite
11
12
async function rewrite(filename: string, lines: string[], eol: string, checkMode: boolean) {
13
  const {length} = lines
14
  , fileExists = await $exists(filename)
15
16
  if (fileExists) {
17
    const lineReader = createInterface({
18
      input: createReadStream(filename),
19
      crlfDelay: Infinity,
20
      historySize: 0
21
    })
22
23
    let isSame = true
24
    , row = 0
25
26
    for await (const line of lineReader) {
27
      if (line !== lines[row]) {
28
        isSame = false
29
        break
30
      }
31
      row++
32
    }
33
34
    lineReader.close()
35
36
    if (isSame) {
37
      if (lines[row] === "")
38
        row++
39
      if (length === row)
40
        return
41
    }
42
  }
43
44
  if (checkMode)
45
    throw Error(`Content of "${filename}" should be another`)
46
47
  const fd = await $open(filename, "w")
48
49
  for (let i = 0; i < length; i++)
50
    await $write(fd, `${
51
      i ? eol : ''
52
    }${
53
      lines[i]
54
    }`)
55
56
  await $close(fd)
57
}
58