Javascript – 配列内のすべての単語を小文字にし、i+1 個の単語の最初の文字を大文字にします。


Javascript – 配列内のすべての単語を小文字にし、i+1 個の単語の最初の文字を大文字にします。

//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'

私が試したこと:

以下のコードは機能しますが、非常に面倒です!

時間の複雑さは 0(1) で、空間の複雑さは… O(3) だと思いますか?
キット全体と kapboodle を完了するのに 1 ミリ秒かかりますが、それは正しくないようです。

1 解決

十分に単純に思えます:

JavaScript
const variableNameify = (words) => words.map((word, index) => index === 0 ? word.toLowerCase() : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join("");

時間を計測したい場合:

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']));

私のマシンでは、実行時間が短すぎて測定できません。 3 つの呼び出しはすべて、0ms かかっていることを示しています。



Source link

コメント

タイトルとURLをコピーしました