# Ten Simple Javascript Exercises

Show 40 post(s) from this thread on one page
Page 3 of 4 First 1234 Last
• 06-10-2009, 06:25 PM
David Harrison
Quote:

Originally Posted by astupidname
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.
• 06-10-2009, 07:28 PM
Four Staples
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>```
• 06-10-2009, 07:32 PM
astupidname
also, newWord is still not defined before attempting to treat it as an array.

Quote:

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');
• 06-10-2009, 09:12 PM
ricem84
Are there programs out there for finding these errors, like how you can validate website code at W3C?
• 06-10-2009, 09:35 PM
Four Staples
Use the Error Console in Firefox. For your last bit of code, Firefox returned the following error:
Quote:

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:
Quote:

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.
• 06-10-2009, 10:20 PM
JMRKER
Simplified version for problem #3
Simplified version for problem #3:
Quote:

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>`
:)
• 06-11-2009, 01:25 PM
Nedals
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 }
• 06-11-2009, 09:46 PM
David Harrison
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.
• 06-12-2009, 12:05 AM
ricem84
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.
• 06-12-2009, 12:24 AM
Four Staples
Quote:

Originally Posted by ricem84
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.
• 06-13-2009, 01:50 PM
ricem84
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.
• 06-13-2009, 03:02 PM
ricem84
Also, I have a bazillion "Warning: Empty string passed to getElementById()." in my Error Console. What are these due to? I never use getElementById().
• 06-13-2009, 03:09 PM
Four Staples
Quote:

Originally Posted by ricem84
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; }```
• 06-13-2009, 04:35 PM
Four Staples
Quote:

Originally Posted by ricem84
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.
• 06-13-2009, 04:45 PM
ricem84
Okay, thanks. I get it now. It's a little confusing, but I think I just need practice.
Show 40 post(s) from this thread on one page
Page 3 of 4 First 1234 Last

## X vBulletin 4.2.2 Debug Information

• Page Generation 0.11362 seconds
• Memory Usage 2,426KB
• Queries Executed 11 (?)
Template Usage (25):
• (11)bbcode_code_printable
• (1)bbcode_html_printable
• (9)bbcode_quote_printable
• (1)footer
• (1)gobutton
• (1)navbar_moderation
• (1)navbar_noticebit
• (2)option
• (1)pagenav
• (1)pagenav_curpage
• (1)spacer_close
• (1)spacer_open

Phrase Groups Available (3):
• global
• postbit
Included Files (19):
• ./global.php
• ./includes/class_bootstrap.php
• ./includes/init.php
• ./includes/class_core.php
• ./includes/config.php
• ./includes/functions.php
• ./includes/class_friendly_url.php
• ./includes/class_hook.php
• ./includes/class_bootstrap_framework.php
• ./vb/vb.php
• ./vb/phrase.php
• ./includes/functions_calendar.php
• ./includes/class_bbcode_alt.php
• ./includes/class_bbcode.php
• ./includes/functions_bigthree.php
• ./includes/functions_notice.php

Hooks Called (43):
• init_startup
• init_startup_session_setup_start
• database_pre_fetch_array
• database_post_fetch_array
• init_startup_session_setup_complete
• global_bootstrap_init_start
• global_bootstrap_init_complete
• cache_permissions
• fetch_foruminfo
• global_state_check
• global_bootstrap_complete
• global_start
• style_fetch
• global_setup_complete
• friendlyurl_resolve_class
• friendlyurl_clean_fragment
• friendlyurl_geturl
• pagenav_page
• cache_templates
• cache_templates_process
• template_register_var
• template_render_output
• fetch_template_start
• fetch_template_complete
• parse_templates