Skip to content

Instantly share code, notes, and snippets.

@isurfer21
Created July 11, 2023 15:56
Show Gist options
  • Save isurfer21/6120c885c7192fd27d8287fefb4311fc to your computer and use it in GitHub Desktop.
Save isurfer21/6120c885c7192fd27d8287fefb4311fc to your computer and use it in GitHub Desktop.
The snake_case to camelCase converter CLI app
// Import the file system module
const fs = require('fs');
// Import the process module
const process = require('process');
// Define a function to convert snake_case to camelCase
function snakeToCamel(str) {
// Split the string by underscore
let words = str.split('_');
// Capitalize the first letter of each word except the first one
let camelWords = words.map((word, index) => {
if (index === 0) {
return word;
} else {
return word[0].toUpperCase() + word.slice(1);
}
});
// Join the words by empty string
return camelWords.join('');
}
// Define a function to check if a string is all capital letters
function isAllCaps(str) {
// Compare the string with its uppercase version
return str === str.toUpperCase();
}
// Define a function to process a JavaScript file
function processFile(fileName) {
// Read the file content as a string
fs.readFile(fileName, 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
// Split the string by whitespace and punctuation
let tokens = data.split(/(\s+|[.,;(){}[\]])/);
// Loop through the tokens and convert snake_case to camelCase if not all caps
let newTokens = tokens.map((token) => {
if (token.includes('_') && !isAllCaps(token)) {
return snakeToCamel(token);
} else {
return token;
}
});
// Join the tokens by empty string
let newData = newTokens.join('');
// Write the new data to a new file
fs.writeFile(fileName + '.camel', newData, 'utf8', (err) => {
if (err) {
console.error(err);
return;
}
console.log('File processed successfully!');
});
});
}
// Get the arguments array from the process object
let args = process.argv;
let argv = args.splice(2);
if (argv.length > 0) {
if (['-h', '--help'].indexOf(argv[0]) >= 0) {
console.log(`Usage:
snake2camel [options] <filename>
Options:
-h --help show help
`);
} else {
// Call the function with a file name as an argument
processFile(argv[0]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment