UNPKG

custom-word-count

Version:

A cli tool which counts word in a given file or count a specific word count when provided in argument.

32 lines (25 loc) 941 B
import { readFile } from 'fs/promises'; const validString = (str) => { return (typeof str === 'string' && str.trim().length > 0) ? true : false; } const filePath = process.argv[2]; const searchInputWord = process.argv[3]; if (validString(filePath)) { const words = await readFile(filePath, 'utf-8'); const wordArray = words.split(/\W/).filter(w => w); let wordCount = {}; // Check if 'search word' is specified if(validString(searchInputWord)){ wordCount[searchInputWord] = wordArray.reduce((count, item) => { return (item.toLowerCase() === searchInputWord.toLowerCase()) ? count + 1 : count; }, 0); }else{ wordCount = wordArray.reduce((acc, word) => { acc[word] = (acc[word] || 0) + 1; return acc; }, {}); } console.log(wordCount); }else { console.log('Please specify the correct file path!!!'); }