Click here to Skip to main content
15,566,994 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
//Write a function variableNameify(words) that takes in an array of words. 
//The function should return a string representing the variable name obtained 
//by combining the words and captitalizing them in mixCased style.



function variableNameify(words) {
    let startTime = new Date();


    firstWord = String(words[0].toLowerCase());
    newArray = capitalize(words.slice(1,words.length));
    newArray.unshift(firstWord)
    console.log(newArray.join(''))

    let endTime = new Date();

    console.log((endTime - startTime) + ' ms')

    return newArray.join('')
    
}

function capitalize(arr) {
    return arr.map(element => {
        return element.charAt(0).toUpperCase() + element.slice(1).toLowerCase()
    })
}


//Tests:

variableNameify(['is', 'prime']) // => 'isPrime'
variableNameify(['remove', 'last', 'vowel']) // => 'removeLastVowel'
variableNameify(['MaX', 'VALUE']) // => 'maxValue'


What I have tried:

The below code works, but it is extremely messy!

I think the Time Complexity is 0(1) and the Space Complexity is... O(3)?
I'm getting 1ms to complete the whole kit and kapboodle, but that doesn't seem right.
Posted
Updated 2-Nov-22 23:40pm

1 solution

Seems simple enough:
JavaScript
const variableNameify = (words) => words.map((word, index) => index === 0 ? word.toLowerCase() : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join("");
If you want to measure the time:
JavaScript
const measureTime = (fn, args) => {
	const startTime = performance.now();
	try {
		return fn.call(this, args);
	} finally {
		const endTime = performance.now();
		console.log("Call to", fn, args, "took", (endTime - startTime), "ms");
	}
};

console.log(measureTime(variableNameify, ['is', 'prime']));
console.log(measureTime(variableNameify, ['remove', 'last', 'vowel']));
console.log(measureTime(variableNameify, ['MaX', 'VALUE']));
On my machine, the execution time is too small to measure; all three calls show it taking 0ms.
 
Share this answer
 
Comments
Chris Aug2022 3-Nov-22 13:52pm    
I appreciate it. It seems so obvious when I read your solution. I haven't had much practice with using the dual return method for true/false. Definitely something I will have to practice.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900