|
| 1 | +// Program to filter lines of a file that include a word and paint the match. Like basic grep command. |
| 2 | +// TODO add cli input |
| 3 | + |
| 4 | +import { readFile } from "node:fs/promises"; |
| 5 | +import chalk from "chalk"; |
| 6 | + |
| 7 | +const main = async () => { |
| 8 | + let text; |
| 9 | + try { |
| 10 | + text = await readFile("history.txt", "utf-8"); |
| 11 | + } catch (error) { |
| 12 | + if (error.code === "ENOENT") { |
| 13 | + console.log("Not such file in path"); |
| 14 | + return |
| 15 | + } else { |
| 16 | + throw error; |
| 17 | + } |
| 18 | + } |
| 19 | + const history = text.split("\n"); |
| 20 | + |
| 21 | + searchWord(history, "node"); |
| 22 | +}; |
| 23 | + |
| 24 | +const searchWord = (arr, word) => { |
| 25 | + arr.forEach((line) => { |
| 26 | + if (line.includes(word)) { |
| 27 | + paintWord(line, word); |
| 28 | + } |
| 29 | + }); |
| 30 | +}; |
| 31 | + |
| 32 | +const paintWord = (text, searchWord) => { |
| 33 | + const matches = [...text.matchAll(new RegExp(searchWord, "gi"))]; |
| 34 | + const startIndexes = matches.map((match) => match.index); |
| 35 | + const indexes = getWordIndexes(startIndexes, searchWord.length); |
| 36 | + |
| 37 | + let word = ""; |
| 38 | + text.split("").forEach((letter, index) => { |
| 39 | + if (indexes.includes(index)) { |
| 40 | + word += chalk.blue(letter); |
| 41 | + } else { |
| 42 | + word += letter; |
| 43 | + } |
| 44 | + }); |
| 45 | + console.log(word); |
| 46 | +}; |
| 47 | + |
| 48 | +const getWordIndexes = (indices, len) => { |
| 49 | + const result = []; |
| 50 | + |
| 51 | + indices.forEach((index) => { |
| 52 | + for (let i = 0; i < len; i++) { |
| 53 | + result.push(index + i); |
| 54 | + } |
| 55 | + }); |
| 56 | + |
| 57 | + return result; |
| 58 | +}; |
| 59 | + |
| 60 | +main(); |
0 commit comments