contador-de-metas 1.0.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/README.md +3 -0
  2. package/contador.js +75 -12
  3. package/date.js +64 -0
  4. package/io.js +12 -0
  5. package/package.json +31 -21
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # Contador de Metas 📋
2
+
3
+ ## Como Usar?
package/contador.js CHANGED
@@ -1,24 +1,54 @@
1
- // import dependecies
2
- const fs = require("fs");
3
- const readline = require("readline");
4
-
5
- const rl = readline.createInterface({
1
+ #!/usr/bin/env node
2
+ // const fs = require("fs");
3
+ // const readline = require("readline");
4
+ import fs from "fs"
5
+ import readline from "readline"
6
+ import { isValidDDMMYYYY } from "./date.js";
7
+ import { extractDateDDMMYYYY } from "./date.js";
8
+ import { readFiles } from "./io.js";
9
+
10
+ const userInput = readline.createInterface({
6
11
  input: process.stdin,
7
12
  output: process.stdout,
8
13
  });
9
14
 
10
- // Cria uma função que retorna uma Promise para perguntar algo ao usuário
11
15
  const askQuestion = (question) => {
12
16
  return new Promise((resolve) => {
13
- rl.question(question, (answer) => {
17
+ userInput.question(question, (answer) => {
14
18
  resolve(answer);
15
19
  });
16
20
  });
17
21
  };
18
22
 
23
+ //Variáveis de configuração
24
+ const endOfToDo = "Nível atual: "
25
+ const fileToDoMarker = "todo"
26
+
27
+ async function findFile() {
28
+ let files = await readFiles();
29
+ let dates = files.filter(file =>{
30
+ if(file.includes(fileToDoMarker)){
31
+ const date = extractDateDDMMYYYY(file)
32
+ if(isValidDDMMYYYY(date)){
33
+ return true
34
+ }
35
+ }
36
+ })
37
+
38
+ const oldestString = dates.reduce((oldest, current) => {
39
+ return parseDate(current) < parseDate(oldest) ? current : oldest;
40
+ });
41
+
42
+ return oldestString;
43
+ }
44
+
45
+ let file = await findFile();
46
+
47
+ console.log("Seria", file, "o arquivo certo?")
48
+
19
49
  // read the text and split it on new lines
20
50
  // const lines = fs.readFileSync("todo-18012025" + ".txt").toString().split("\r\n");
21
- const lines = fs.readFileSync(".todo-16112025" + ".txt").toString().split("\n");
51
+ const lines = fs.readFileSync(`${file}`).toString().split("\n");
22
52
  // const lines = fs.readFileSync("Novo Documento" + ".txt").toString().split("\n");
23
53
 
24
54
  // All of the parse topics
@@ -46,6 +76,7 @@ const regexNovaMeta = /^[ \t]*-.*/;
46
76
  // linhas que começam com traços mas pode ter tabulações ou espaços antes.
47
77
 
48
78
  (async () => {
79
+
49
80
  for(let i = 0; i<lines.length; i+=1){
50
81
  if(lines[i].match(regexNovaMeta)){
51
82
  oldchanges.push(lines[i])
@@ -54,6 +85,7 @@ const regexNovaMeta = /^[ \t]*-.*/;
54
85
  }
55
86
  }
56
87
  console.log(contadorNovaMeta, "novas metas ontem.")
88
+
57
89
  const resposta1 = await askQuestion("Deseja continuar?")
58
90
 
59
91
  let updatedLines
@@ -80,6 +112,7 @@ const regexNovaMeta = /^[ \t]*-.*/;
80
112
  }
81
113
  }
82
114
  console.log(contadorConclusao, "concluídos ontem.")
115
+
83
116
  const resposta2 = await askQuestion("Deseja continuar?")
84
117
 
85
118
  if(resposta2 == 1 && resposta2 == 1){
@@ -95,15 +128,45 @@ const regexNovaMeta = /^[ \t]*-.*/;
95
128
  return line;
96
129
  });
97
130
  // console.log(updatedLines)
131
+
132
+ addNovoNivel(updatedLines, contadorConclusao, contadorNovaMeta);
98
133
 
99
- let txt = updatedLines.join("\n")
100
- // console.log(txt)
101
- fs.writeFileSync('Novo Documento' + '.txt', txt)
134
+ let filedata = updatedLines.join("\n")
135
+ // console.log(filedata, "o texto acima")
136
+ // console.log(updatedLines, "updatedlines")
137
+ fs.writeFileSync('Novo Documento' + '.txt', filedata)
102
138
  }
103
139
 
104
- rl.close()
140
+ userInput.close()
105
141
  console.log(oldchanges)
106
142
  console.log("-" + contadorConclusao + "-" + contadorNovaMeta + "-")
107
143
  })();
108
144
 
145
+ function addNovoNivel(lines, numConclusao, numNovaMeta){
146
+ for (let i = lines.length - 1; i >= 0; i--) {
147
+ const line = lines[i];
148
+
149
+ if (line.includes(endOfToDo)) {
150
+ const arrayStringsDoFim = line.match(/\d+/g); //inteiros
151
+ const arrayNumerosDoFim = arrayStringsDoFim.map(Number);
152
+
153
+ // console.log("antes:", lines[i])
154
+ lines[i] = endOfToDo + (arrayNumerosDoFim[0] + numConclusao) + "-" + (arrayNumerosDoFim[1] + numNovaMeta)
155
+ // console.log("depois:", lines[i])
156
+
157
+ console.log(JSON.stringify(lines[i-1]))
158
+ // lines[i-1].replace(/\\r/g, ("-" + numConclusao + "-" + numNovaMeta + "-" + '\n'))
159
+ lines[i-1] = lines[i-1].replace('\r', '') + (" -" + numConclusao + "-" + numNovaMeta + "-")
160
+ console.log(JSON.stringify(lines[i-1]))
161
+
162
+ addProximoDia(lines, i)
163
+
164
+ i = -1
165
+ }
166
+ }
167
+ }
168
+
169
+ function addProximoDia(lines, index){
170
+ lines.splice(index, 0, '')
171
+ }
109
172
 
package/date.js ADDED
@@ -0,0 +1,64 @@
1
+ export function isValidDDMMYYYY(dateString) {
2
+ // 1. Verificar o formato usando uma expressão regular (ddmmyyyy)
3
+ // Garante exatamente 8 dígitos numéricos
4
+ const formatRegex = /^\d{8}$/;
5
+ if (!formatRegex.test(dateString)) {
6
+ return false;
7
+ }
8
+
9
+ // 2. Extrair dia, mês e ano da string
10
+ const day = parseInt(dateString.substring(0, 2), 10);
11
+ const month = parseInt(dateString.substring(2, 4), 10);
12
+ const year = parseInt(dateString.substring(4, 8), 10);
13
+
14
+ // 3. Verificar os limites básicos (mês entre 1 e 12, dia entre 1 e 31)
15
+ if (month < 1 || month > 12 || day < 1 || day > 31) {
16
+ return false;
17
+ }
18
+
19
+ // 4. Verificar o número de dias em meses específicos (incluindo anos bissextos)
20
+ const daysInMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
21
+
22
+ // Lógica para ano bissexto:
23
+ // Um ano é bissexto se for divisível por 4, exceto se for divisível por 100,
24
+ // mas não se for divisível por 400.
25
+ if (year % 400 === 0 || (year % 100 !== 0 && year % 4 === 0)) {
26
+ daysInMonth[2] = 29;
27
+ }
28
+
29
+ // Verificar se o dia está dentro do intervalo válido para o mês e ano específicos
30
+ if (day > daysInMonth[month]) {
31
+ return false;
32
+ }
33
+
34
+ // Se todas as verificações passarem, a data é válida
35
+ return true;
36
+ }
37
+
38
+ // Exemplos de uso:
39
+ // console.log(`"25122024" é válido? ${isValidDDMMYYYY("25122024")}`); // true
40
+ // console.log(`"31022024" é válido? ${isValidDDMMYYYY("31022024")}`); // false (fevereiro só tem 29 dias em 2024)
41
+ // console.log(`"29022024" é válido? ${isValidDDMMYYYY("29022024")}`); // true (2024 é bissexto)
42
+ // console.log(`"29022023" é válido? ${isValidDDMMYYYY("29022023")}`); // false (2023 não é bissexto)
43
+ // console.log(`"010124" é válido? ${isValidDDMMYYYY("010124")}`); // false (formato incorreto, apenas 6 dígitos)
44
+ // console.log(`"abcde" é válido? ${isValidDDMMYYYY("abcde")}`); // false (não é numérico)
45
+ // console.log(`"12122024" é válido? ${isValidDDMMYYYY("12122024")}`); // true
46
+
47
+ export function extractDateDDMMYYYY(string){
48
+ try {
49
+ const reDDMMYYYY = /(\d{2})(\d{2})(\d{4})/;
50
+ const correspondencia = string.match(reDDMMYYYY);
51
+ return correspondencia[0]
52
+ } catch (err) {
53
+ return false;
54
+ }
55
+ }
56
+
57
+ export function parseDate(str) {
58
+ const digits = str.replace(/\D/g, ""); // remove letras
59
+ const day = Number(digits.slice(0, 2));
60
+ const month = Number(digits.slice(2, 4)) - 1; // JS começa em 0
61
+ const year = Number(digits.slice(4, 8));
62
+
63
+ return new Date(year, month, day);
64
+ }
package/io.js ADDED
@@ -0,0 +1,12 @@
1
+ import fs from "fs/promises"
2
+
3
+ export async function readFiles() {
4
+ try {
5
+ const arquivos = await fs.readdir('.');
6
+ return arquivos;
7
+ } catch (err) {
8
+ console.error('Erro ao ler o diretório:', err);
9
+ }
10
+ }
11
+
12
+
package/package.json CHANGED
@@ -1,21 +1,31 @@
1
- {
2
- "name": "contador-de-metas",
3
- "version": "1.0.0",
4
- "description": "",
5
- "main": "contador.js",
6
- "type": "module",
7
- "files": ["contador.js"],
8
- "scripts": {
9
- "test": "echo \"Error: no test specified\" && exit 1"
10
- },
11
- "repository": {
12
- "type": "git",
13
- "url": "git+https://github.com/caio-venancio/contador-de-metas.git"
14
- },
15
- "author": "Caio Venâncio",
16
- "license": "ISC",
17
- "bugs": {
18
- "url": "https://github.com/caio-venancio/contador-de-metas/issues"
19
- },
20
- "homepage": "https://github.com/caio-venancio/contador-de-metas#readme"
21
- }
1
+ {
2
+ "name": "contador-de-metas",
3
+ "version": "1.3.0",
4
+ "description": "",
5
+ "main": "contador.js",
6
+ "type": "module",
7
+ "files": [
8
+ "contador.js",
9
+ "date.js",
10
+ "io.js"
11
+ ],
12
+ "scripts": {
13
+ "test": "echo \"Error: no test specified\" && exit 1"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/caio-venancio/contador-de-metas.git"
18
+ },
19
+ "author": "Caio Venâncio",
20
+ "license": "ISC",
21
+ "bugs": {
22
+ "url": "https://github.com/caio-venancio/contador-de-metas/issues"
23
+ },
24
+ "homepage": "https://github.com/caio-venancio/contador-de-metas#readme",
25
+ "dependencies": {
26
+ "contador-de-metas": "^1.0.0"
27
+ },
28
+ "bin": {
29
+ "contador": "./contador.js"
30
+ }
31
+ }