All files / src/pretty_printer remove_sequential_blanks.ts

100% Statements 58/58
100% Branches 16/16
100% Functions 6/6
100% Lines 58/58

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 581x 1x 1x 1x 1x 1x 1x 1x 28x 28x 1x 1x 28x 28x 26x 26x 2x 2x 2x 1x 1x 26x 26x 26x 26x 26x 75x 26x 26x 26x 75x 75x 75x 8x 8x 17x 10x 17x 7x 7x 17x 8x 75x 26x 26x 1x 26x 26x 75x 26x 26x 26x 26x 1x 1x 28x 28x 1x
import {SequentialBlankConf, SequentialBlank} from "../rules";
import {IFile} from "../files/_ifile";
import {IConfiguration} from "../_config";
 
export class RemoveSequentialBlanks {
  private readonly config: IConfiguration;
 
  public constructor(config: IConfiguration) {
    this.config = config;
  }
 
  public execute(file: IFile, modified: string): string {
    const sequentialBlankConfig = this.getSequentialBlankConfig();
    if (sequentialBlankConfig) {
      return this.withoutSequentialBlanks(file, modified, sequentialBlankConfig.lines);
    }
 
    return modified;
  }
 
  private withoutSequentialBlanks(file: IFile, modified: string, threshold: number): string {
    const rows = file.getRawRows();
 
    let blanks = 0;
    const rowsToRemove: number[] = [];
    const newBlankCount = (current: number, row: string): number => {
      return SequentialBlank.isBlankOrWhitespace(row) ? current + 1 : 0;
    };
 
    for (let i = 0; i < rows.length; i++) {
      blanks = newBlankCount(blanks, rows[i]);
 
      if (blanks === threshold) {
        // count additional blanks
        for (let j = i; j < rows.length; j++) {
          if (SequentialBlank.isBlankOrWhitespace(rows[j])) {
            rowsToRemove.push(j);
          } else {
            break;
          }
        }
      }
    }
    return this.removeRows(modified.split("\n"), rowsToRemove);
  }
  private removeRows(lines: string[], rowsToRemove: number[]): string {
 
    const withoutRemoved = lines.filter((_, idx) => {
      return rowsToRemove.indexOf(idx) === -1;
    });
 
    return withoutRemoved.join("\n").trim();
  }
 
  private getSequentialBlankConfig(): SequentialBlankConf | undefined {
    return this.config.readByRule(new SequentialBlank().getMetadata().key);
  }
}