HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Various simple JavaScript solutions

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
javascriptsolutionssimplevarious

Problem

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 function multiply() that sums and
multiplies (respectively) all the numbers in an array of numbers. For
example, sum([1,2,3,4]) should return 10, and multiply([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 count)

Solution

Here one way to sum a list of integers using ECMAScript 5's functional support

// Sum all values in a list by reducing the list to a single value
array.reduce(function(prev, curr) {
  return prev + curr;
});


Not faster than your approach due to the repeated function calls, but definitely shorter.

Your approach can be further simplified:

// Move everything into the parenthesis of for-loop!
var sum = function(array) {
  for (
    var i = 0, len = array.length, total = 0; 
    i < len; 
    total += array[i++]
  );
  return total;
};


Not recommended because it's not very readable. I just think it's interesting :)

I'll give you an alternative approach to the "Find length of longest string" problem:

// Sort it by length descending and then get the first
var longestStrLen = array.sort(function(a, b) {
    a.length - b.length;
})[0].length;


Hope these open your eyes to some of the possibilities!

Now, here's an actual review:

var charFreq = function(string){
  var list = {}; // Not a list (implies order). Should name it a dictionary or map
  var length = string.length; // no need to have this be separate line
  for (var i = 0; i < length; i++) {  
  if (string.charAt(i) in list) 
    // What's with the +1??
    list[string.charAt(i)] += +1;
  else 
    // No need to call string.charAt multiple times!
    list[string.charAt(i)] = 1;
  }
  return list;
}


Revised version:

var charFreq = function(string){
  var dict = {}; 
  for (var i = 0, len = string.length; i < len; i++) {
    var currChar = string.charAt(i);  
    if (currChar in dict) { 
      dict[currChar] += 1;
    } else {
      dict[currChar] = 1;
    }
  }
  return dict;
}


Hope that helps!

Code Snippets

// Sum all values in a list by reducing the list to a single value
array.reduce(function(prev, curr) {
  return prev + curr;
});
// Move everything into the parenthesis of for-loop!
var sum = function(array) {
  for (
    var i = 0, len = array.length, total = 0; 
    i < len; 
    total += array[i++]
  );
  return total;
};
// Sort it by length descending and then get the first
var longestStrLen = array.sort(function(a, b) {
    a.length - b.length;
})[0].length;
var charFreq = function(string){
  var list = {}; // Not a list (implies order). Should name it a dictionary or map
  var length = string.length; // no need to have this be separate line
  for (var i = 0; i < length; i++) {  
  if (string.charAt(i) in list) 
    // What's with the +1??
    list[string.charAt(i)] += +1;
  else 
    // No need to call string.charAt multiple times!
    list[string.charAt(i)] = 1;
  }
  return list;
}
var charFreq = function(string){
  var dict = {}; 
  for (var i = 0, len = string.length; i < len; i++) {
    var currChar = string.charAt(i);  
    if (currChar in dict) { 
      dict[currChar] += 1;
    } else {
      dict[currChar] = 1;
    }
  }
  return dict;
}

Context

StackExchange Code Review Q#49375, answer score: 4

Revisions (0)

No revisions yet.