Passed
Push — master ( 0549a3...50b922 )
by Andrii
02:48
created

rewrite.ts ➔ rewrite   C

Complexity

Conditions 10

Size

Total Lines 48
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

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