www.webdeveloper.com
Page 3 of 4 FirstFirst 1234 LastLast
Results 31 to 45 of 56

Thread: Ten Simple Javascript Exercises

  1. #31
    Join Date
    Dec 2002
    Location
    Manchester, UK
    Posts
    6,276
    Quote Originally Posted by astupidname View Post
    I saw another post here once where someone wrote their 'vowel' program to include 'y' as a vowel at random. That is dead wrong also, so don't do that either.
    Heh, I don't think you understood the spirit that Charles posted it in.

    But y is never a vowel. Ever.

    Rhythm is a word that has no vowels in.

    Quote Originally Posted by http://www.decoz.com/Y_vowel-consonant.htm
    The vowels reveal the tender you, your love, caring , and vulnerability. Consonants reveal certain of your characteristics that, among other things, shield your more vulnerable parts.
    BAHAHAHA, numerology is such total crap. "In partnership with tarot.com", yeah, well that figures.

    I don't really want to drag this away from coding though, so hypocritically if this runs off topic I'll just start deleting posts.
    Every fight is a food fight when you’re a cannibal.

  2. #32
    Join Date
    Jun 2009
    Posts
    111
    On line 17 you had an if open brace { and it wasn't closed until after your else statement. I removed them, but if you want to add them back in, put the closing brace before else, then a new one for the else statement.
    HTML Code:
    <html>
    <head>
    
    <script language="javascript">
    
    function findType(chara){
    var vowels=new Array();
    vowels[0]='a';
    vowels[1]='e';
    vowels[2]='i';
    vowels[3]='o';
    vowels[4]='u';
    vowels[5]='y';
    for(i=0;i<6;i++){
    if(chara==vowels[i])
    	return true;
    else
    	return false;
    
    }
    }
    
    function translate()
    {
    	var w=prompt("Enter a word:","");
    	var newWord;
    	var k = 0;
    	word = w.split("");
    	for (var j=0; j<word.length; j++)
    	{
    		newWord[k] = word[j];
    		k++;
    		if (!findType(word[j]))
    		{
    			newWord[k] = "o";
    			k++;
    			newWord[k] = word[j];	
    			k++;
    		}			
    	}
    		
    	newWord.join();
    	alert(newWord);
    	
    }
    
    translate();
    </script>
    
    </head>
    <body>
    
    </body>
    </html>

  3. #33
    Join Date
    Oct 2008
    Location
    U.S.
    Posts
    726
    also, newWord is still not defined before attempting to treat it as an array.

    When you create a new array, can you add on to the end of it without defining a length for it?
    Yes array's have a push() method, such as:
    var myArray = [];
    myArray.push('some text');

  4. #34
    Join Date
    Jun 2009
    Posts
    23
    Are there programs out there for finding these errors, like how you can validate website code at W3C?

  5. #35
    Join Date
    Jun 2009
    Posts
    111
    Use the Error Console in Firefox. For your last bit of code, Firefox returned the following error:
    Syntax error
    Line 17
    else
    Which indicated there was a problem with where your "else" was positioned... I noticed you had put a closing brace after the IF, but there was no closing brace before ELSE. I removed the one after IF and Firefox gave this error:
    Syntax error
    Line 21
    }
    Which indicated there was a closing brace but no opening brace, so I figured you must have had an opening and closing brace before, just in the wrong places. I removed the closing brace and the script worked.

    Also, you should indent your code so that you can see the blocks... like this:
    Code:
    if(something == somethingelse) {
    	doThis();
    	andDoThis();
    	if(something == anothersomethingelse) {
    		doThisPlease();
    	}
    }
    And when you're closing off your curly braces, you'll always know if you're missing one, because there will be a tab without a closing brace on it. It also helps for visualizing where your different "blocks" of code are.

  6. #36
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,435

    Lightbulb Simplified version for problem #3

    Simplified version for problem #3:
    3. Write a function that takes a character (i.e. a string of length 1)
    and returns true if it is a vowel, false otherwise.
    Code:
    function isVowel(c) {
      c = c.toLowerCase();
      if ('aeiou'.indexOf(c) == -1) { return false; } else { return true; }
    }
    function Solution3() {
      var c = prompt('Enter a VOWEL or a CONSONANT');
      alert(c+' is a vowel: '+isVowel(c));	
    }
    Call in HTML like:
    Code:
    <button onclick="Solution3()">Solution #3</button>

  7. #37
    Join Date
    Dec 2002
    Location
    Pleasanton, CA
    Posts
    2,132
    Just for fun, how short can you make the solution to each problem.
    Code:
    eg:
    function translate(str) {
    return str.replace(/([^aeiou\s])/g,"$1o$1")    ....  44 char
    }
    1.Define a function max() that takes two numbers as arguments and returns the largest of them. Use the ternary(sic) construct available in Javascript.
    function max2(x1,x2) { 21 char }

    2.Define a function maxOfThree() that takes three numbers as arguments and returns the largest of them.
    function max3(x1,x2,x3) { 39 char }

    3.Write a function that takes a character (i.e. a string of length 1) and returns true if it is a vowel, false otherwise.
    function vowel(char) { 41 char }

    4.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".
    function translate(str) { 44 char }

    5.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.
    function sum(ary) { 52 char }
    function mult(ary) { 52 char }

    6.Define a function reverse() that computes the reversal of a string. For example, reverse("jag testar") should return the string "ratset gaj".
    function reverse(str) { 42 char }

    7.Write a function to sort a list of words (an array) in alphabetical order
    function wordsort(ary) { 18 char }

    8.Write a function findLongestWord() that takes an array of words and returns the length of the longest one.
    function findLongestWord(ary) { 84 char }

    9.Write a function filterLongWords() that takes an array of words and an integer i and returns the array of words that are longer than i.
    function findLongest(ary,len) { 91 char }

    10.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 like charFreq("abbabcbdbabdbdbabababcbcbab").
    function charFreq(str) { 116 char }

  8. #38
    Join Date
    Dec 2002
    Location
    Manchester, UK
    Posts
    6,276
    I'll report scores here for me, and for Milkman who I conversed with on MSN. Where there's only one score, either we got the same, or he didn't do that one.

    1. 14 chars

    2. If it's allowed to use the first function in the second, I got 23 chars, if not then I got 26 chars. Milkman totally blew me away with 23 chars without using the first function.
    Code:
    function max3(x,y,z){return x>y?x>z?x:z:y>z?y:z}
    function max3(a,b,c){return(x=a>b?a:b)>c?x:c}
    2.5. Define a function that takes a variable length array of numbers as an argument and returns the largest of them.

    I got 43 chars, Milkman got 41 chars.

    3. 25 chars

    4. I got 1 longer at 45 chars, Milkman got 49, but ours work better. Try your function out with the string "This _is_ FUN!" This is our code for this one:
    Code:
    function translate(a){return a.replace(/([^\W\daeiou_])/gi,"$1o$1")}
    function translate(a){return a.replace(/([bcdfghj-np-tv-z])/gi,'$1o$1')}
    Perhaps this should be amended to put the letter o between all consonants, and also, when the consonant is upper case, so must the o be. At the moment my function for that is 86 characters. I'm positive that can be reduced significantly.

    5. 24 chars for both, these functions are practically identical.

    6. 37 chars

    7. Using the built in sort method, 15 chars. Without using that, 92 chars.

    8. 45 chars

    9. 56 chars for me, 52 for Milkman.

    10. And again, 56 chars for me, 52 for Milkman.
    Last edited by David Harrison; 06-12-2009 at 01:28 AM.
    Every fight is a food fight when you’re a cannibal.

  9. #39
    Join Date
    Jun 2009
    Posts
    23
    Okay, I finished 4 using a bazillion characters.

    Code:
    <html>
    <head>
    
    <script language="javascript">
      
    
    function findType(chara){
    	if (chara == "a" || chara == "e" || chara == "i" || chara == "o" || chara == "u")
    		return true;
    	else
    		return false;
    }
    
    function translate()
    {
    	var w=prompt("Enter a word:");
    	var newWord = new Array();
    	var k = 0;
    	var word = w.split("");
    	for (var j=0; j<word.length; j++)
    	{
    		newWord[k] = word[j];
    		k++;
    		if (!findType(word[j]))
    		{
    			newWord[k] = "o";
    			k++;
    			newWord[k] = word[j];	
    			k++;
    		}			
    	}
    	newWord.join();
    	alert(newWord);
    }
    
    translate();
    </script>
    
    </head>
    <body>
    
    </body>
    </html>
    Turned out my vowel code didn't work either. I'd copied it from the thread similar to this one. One question I have is how to remove the commas from alert(newword). I thought join() would do that. Thanks for the Error Console info and stupid mistake corrections. Why don't I have to declare "chara" as in "var chara"?

    I guess I should learn that ehiaoethea/W/^ stuff so I can understand your guys' solutions. I have some Javascript books with me, so it should be in there.

    What do I call this stuff: x>y?x>z?x:z:y>z?y:z so I can look it up.

  10. #40
    Join Date
    Jun 2009
    Posts
    111
    Quote Originally Posted by ricem84 View Post
    What do I call this stuff: x>y?x>z?x:z:y>z?y:z so I can look it up.
    That's called a ternary operator (well, it's a lot of them strung together and compressed to look like a horse's rectum).

    The "ehiaoethea/W/^ stuff" are Regular Expressions.

  11. #41
    Join Date
    Jun 2009
    Posts
    23
    Code:
    function max3(x,y,z){return x>y?x>z?x:z:y>z?y:z}
    Can somebody explain this to me? I get what one : in an equation means but I don't know what x>y?x>z?x:z:y means.

    Nedals, are you going to share your solutions? I am especially interested in #7. That one looks like a pain in the butt but apparently isn't.
    Last edited by ricem84; 06-13-2009 at 03:33 PM.

  12. #42
    Join Date
    Jun 2009
    Posts
    23
    Also, I have a bazillion "Warning: Empty string passed to getElementById()." in my Error Console. What are these due to? I never use getElementById().

  13. #43
    Join Date
    Jun 2009
    Posts
    111
    Quote Originally Posted by ricem84 View Post
    Code:
    function max3(x,y,z){return x>y?x>z?x:z:y>z?y:z}
    Can somebody explain this to me? I get what one : in an equation means but I don't know what x>y?x>z?x:z:y means.
    I'll expand it for you.
    Code:
    function max3(x,y,z) {
        return (x > y) ?                            // "ternary #1"
                           (x > z) ? x : z           // "ternary #2" returns a value to ternary #1's TRUE result
                           : (y > z) ? y : z        // "ternary #3" returns a value to ternary #1's false result
    }
    It's the same as doing this:
    Code:
    if(x > y) {
        if(x > z)
            return x;
        else
            return z;
    }
    else {
        if(y > z)
            return y;
        else
            return z;
    }

  14. #44
    Join Date
    Jun 2009
    Posts
    111
    Quote Originally Posted by ricem84 View Post
    Also, I have a bazillion "Warning: Empty string passed to getElementById()." in my Error Console. What are these due to? I never use getElementById().
    Other pages. Just clear your error console before you load the page to see what errors your page generates.

  15. #45
    Join Date
    Jun 2009
    Posts
    23
    Okay, thanks. I get it now. It's a little confusing, but I think I just need practice.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles