Home > OS >  wrap a function in javascript
wrap a function in javascript

Time:12-26

let str = "i am writing an algorithm.";

//function to count alphabets
const alphabet_count = (str) => str.length;

//function to count words
const word_count = (str) => str.split(" ").length;

//function to count vowel
const vowel_count = (str) => (str.match(/[aeiou]/gi)).length;

//here i am trying to wrap all three functions in one
const sentence_read() = {alphabet_count(), word_count(), vowel_count()};

I am trying to trying to wrap all three functions in one.

CodePudding user response:

const sentence_read = (str) => [alphabet_count(str), word_count(str), vowel_count(str)]

will return an array with your 3 results. Usage :

let str = "a word";
console.log(sentence_read(str)) // output : [6, 2, 2]

CodePudding user response:

You can wrap them in an object like this:

const counter = {
    alphabet: alphabet_count,
    word: word_count,
    vowel: vowel_count,
}

And then use this object in a function that accepts 2 inputs; 1. 'counting unit' & 2. 'string'.

const count  = (unit, str) => {
    if(!counter[unit]) throw Error('Unit does not exist')
    return counter[unit](str)
}

CodePudding user response:

Using a template string

let str = "i am writing an algorithm.";

// function to count alphabets
const alphabet_count = (str) => str.length;

// function to count words
const word_count = (str) => str.split(" ").length;

//function to count vowel
const vowel_count = (str) => (str.match(/[aeiou]/gi)).length;

const sentence_read = (str) => `a_c : ${alphabet_count(str)}, w_c : ${word_count(str)}, v_c : ${vowel_count(str)}`

console.log(sentence_read(str)) // a_c : 26, w_c : 5, v_c : 8

  • Related