-
Notifications
You must be signed in to change notification settings - Fork 0
/
nameCapitalizer.js
66 lines (57 loc) · 1.88 KB
/
nameCapitalizer.js
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
58
59
60
61
62
63
64
65
66
/*
Obj-nameCapitalizer:
--------------
This simple tool takes a `.txt` file that contains objects and properly capitalize names in it.
Outputs a new converted `.txt` file.
Built to be used with my randsGenerator tool (but can be used without it with minor code tweaking).
--------------
Author: Samuel Poplovitch
*/
// Dependencies
const readline = require('readline');
const fs = require('fs');
// Variables
const fileName = process.argv[2];
const KEY_NAME = 'name'; // <--- the key of the values we will convert
if (fileName) {
const rl = readline.createInterface({
input: fs.createReadStream(fileName)
});
// read line
rl.on('line', function (line) {
// uses KEY_NAME as the key to the value to be changed (assuming objects containing lines of this structure: `KEY_NAME: 'john doe',`)
if (line.indexOf(KEY_NAME) !== -1) {
let vStart;
if (line.indexOf("\"") !== -1)
vStart = line.indexOf("\"");
if (line.indexOf("'") !== -1)
vStart = line.indexOf("'");
//splits the line to the key and values
let value = line.substr(vStart + 1);
let key = line.substr(0, line.length - value.length);
// capitalize first letters of value string
let vConverted = capitalizeFirstLetter(value);
// write to file
writeOut(key + vConverted);
} else writeOut(line);
});
} else console.log("Please enter file name as an arg");
// splits the string and capitalize the first letter of each word
function capitalizeFirstLetter(str) {
str = str.toLowerCase();
var cArr = [];
var splitStr = str.split(" ");
for (var i = 0; i < splitStr.length; i++) {
cArr.push(splitStr[i][0].toUpperCase() + splitStr[i].slice(1));
}
return cArr.join(" ");
}
// write the line to the file
function writeOut(line) {
fs.appendFileSync("./converted_" + fileName, line + '\r\n', (error) => {
if (error) throw error;
});
}
// console log to the user
if (fileName)
console.log("Converting: " + fileName);