Passed
Push — master ( c1d503...0431b4 )
by Andrii
02:39
created

rewrite.ts ➔ rewrite   C

Complexity

Conditions 10

Size

Total Lines 54
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 45
dl 0
loc 54
rs 5.9999
c 0
b 0
f 0
cc 10

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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, truncate } from 'fs'
3
import {createInterface} from 'readline'
4
import { $exists } from "./utils"
5
6
const $open = promisify(open)
7
, $write = promisify(writeFile)
8
, $truncate = promisify(truncate)
9
, $close = promisify(close)
10
11
export = rewrite
12
13
// TODO #12 with .trim() https://jsbench.me/fykmaajqmc/
14
15
async function rewrite(filename: string, lines: string[], eol: string, checkMode: boolean) {
16
  const {length} = lines
17
  , {length: eolLength} = eol
18
  , fileExists = await $exists(filename)
19
20
  let row = 0
21
  , position = 0
22
23
  if (fileExists) {
24
    const lineReader = createInterface({
25
      input: createReadStream(filename),
26
      crlfDelay: Infinity,
27
      historySize: 0
28
    })
29
30
    let isSame = true
31
32
    for await (const line of lineReader) {
33
      if (line !== lines[row]) {
34
        isSame = false
35
        continue
36
      }
37
      row++
38
      position += line.length
39
    }
40
41
    lineReader.close()
42
43
    if (isSame) {
44
      if (lines[row] === "")
45
        row++
46
      if (length === row)
47
        return
48
    }
49
50
    !checkMode && await $truncate(filename, position + eolLength * (row - 1))
51
  }
52
53
  if (checkMode)
54
    throw Error(`Content of "${filename}" should be another`)
55
56
  const fd = await $open(filename, "a")
57
58
  for (let i = row; i < length; i++)
59
    await $write(fd, `${
60
      i ? eol : ''
61
    }${
62
      lines[i]
63
    }`)
64
65
  await $close(fd)
66
}
67