Please critique my solutions to these simple exercises. I have no programming experience, so the more anal you are, the more I'll learn. I'm teaching myself, this is not for school:
Write a function
translate()
that will translate a text into "rövarspråket". That is, double every consonant and place an occurrence of "o" in between. For example,translate("this is fun")
should return the string "tothohisos isos fofunon".
var translate = function(x) {
var string = x.toLowerCase();
var vowels = ["a", "e", "i", "o", "u", " "];
var y = "";
for (i = 0; i < string.length; i++) {
var current = string.charAt(i);
if (vowels.indexOf(current) != -1)
y = (y + (current));
else
y = (y + (current + "o" + current));
}
return y;
}
Define a function
sum()
and a functionmultiply()
that sums and multiplies (respectively) all the numbers in an array of numbers. For example,sum([1,2,3,4])
should return 10, andmultiply([1,2,3,4])
should return 24.
var sum = function(array) {
var length = array.length;
var total = 0;
for (i = 0; i < length; i++) {
total += array[i];
}
return total;
};
var multiply = function(array) {
var length = array.length;
var total = 1;
for (i = 0; i < length; i++) {
total *= array[i];
}
return total;
};
Define a function
reverse()
that computes the reversal of a string. For example,reverse("jag testar")
should return the string "ratset gaj".
var reverse = function(string) {
var length = string.length;
var reversed = [];
var joined = ("");
for (i = length; i > 0; i--){
reversed.push(string.charAt(i-1));
};
for (i = 0; i < (length) ; i++){
joined += (reversed[i]);
}
return joined;
}
Write a function
findLongestWord()
that takes an array of words and returns the length of the longest one.
var findLongestWord = function(array) {
var elements = array.length;
var count = 0;
for (i = 0; i < elements; i++) {
if (array[i].length > count)
count = array[i].length;
}
return count;
}
Write a function
filterLongWords()
that takes an array of words and an integeri
and returns the array of words that are longer thani
.
var filterLongWords = function(array, int){
var length = array.length;
var longestWords = [];
for (i = 0; i < length; i++) {
if (array[i].length > int) {
longestWords[longestWords.length] = array[i];
}
}
return longestWords;
}
Write a function
charFreq()
that takes a string and builds a frequency listing of the characters contained in it. Represent the frequency listing as a JavaScript object. Try it with something likecharFreq("abbabcbdbabdbdbabababcbcbab")
.
var charFreq = function(string){
var list = {};
var length = string.length;
for (var i = 0; i < length; i++) {
if (string.charAt(i) in list)
list[string.charAt(i)] += +1;
else
list[string.charAt(i)] = 1;
}
return list;
}
EDIT: I forgot to mention that rather than use global methods, I tried to as much as possible code for the result I wanted, like reverse, and join, etc.
function reverseString(value) { return value.split('').reverse().join(''); }
\$\endgroup\$