1

I am playing with my friends on internet

we ask each other to say ( name, or animal, or inanimate) begins with a particular letter

So I am thinking about building a page to help me in training about this game

This is an php code for example:

function getNamesByChars($chars,$type='name'){
    $names=array(
    'd'=>'Dan',
    'j'=>'John',
    );
    $animals=array(
    'd'=>'Dog',
    'j'=>'Jar',
    );

    $chars=explode(' ',$chars);    
    foreach($chars as $char){
        //if it a name
        if($type=='name')
        $results.=$names[$char];
        //if it animal
        elseif($type=='animal')
        $results.=$animals[$char];
    }
}
    getNamesByChars('j d','animal');
    //results (Jar dog)

the problem here that i need to make this page faster as much as possible

PHP requires loading the page

i Think javascript is the faster way

but i am very beginner in javascript so i can't build this function

Any help in building this function in javascript?

6
  • Have a look at this question. Commented Mar 4, 2013 at 11:51
  • If your friends know how to view the source of the page all words will be visible. Commented Mar 4, 2013 at 11:52
  • @Minko Gechev Nobody will see this page except me, it will be like a programe Commented Mar 4, 2013 at 11:55
  • Why would Javascript be faster than PHP? Why do you need it faster? Commented Mar 4, 2013 at 12:02
  • Because this game is based on speed, the prime of the game puts some characters, And we get the answer, Everybody get the answer, so the faster is the winner, php requires page reload, so it cost me time, Javascript will get the answer and automatically copy it, i just have to paste the answer Commented Mar 4, 2013 at 12:13

3 Answers 3

2

Here it is but you should read a tuto if you really wanna know javascript....

function getNamesByChars(chars,type){
   type = type || 'name';
   var things = { name: {'d': 'dan', 'j': 'john'},
                  animal:  {'d': 'dog', 'j': 'jar'}};
   var results = [];
   var charsarr = chars.split(' ');
   for (var i in charsarr) {
      results.push(things[type][charsarr[i]]);  
   }
   return results;
}

Ideally there should be some checking if a key doesn't exist but as only you will use it...

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much it's working so fine And thank you very much for your advice I have just started to learn JavaScript, but I did not get to this stage
well that was the perfect exercise to get started ;)
i am still in the variables stage
1

It's a coversion of your php function in js

function getNamesByChars( chars,type ){

   type = type || 'name';

   var names = { 'd':'Dan', 'j':'John' },
       animals = { 'd':'Dog', 'j': 'Jar' };
       results = '';

   var chars = chars.split(' ');

   for( var i=0,len = chars.length; i< len ;i++ ){

       if( type == 'name'){

           results += names[ chars[i]];

       } else if( type == 'animal'){

           results += animals[ chars[i]];       

       }

   }

   return results ;

}

and print result in console

console.log( getNamesByChars('j d','animal') );

or alert

alert( getNamesByChars('j d','name') );

Comments

1

I went totally overkill on this :) fun problem, hope it teaches you something.

See on JSFiddle

HTML

<div>
    <label for="chars">Chars:</label>
    <input id="chars" type="text" />
</div>
<div>
    <input id="names" type="radio" name="names-radio" checked />
    <label for="names">Names</label>
    <input id="animals" type="radio" name="names-radio" />
    <label for="animals">Animals</label>
</div>
<button id="get-names">Get values!</button>

<div>
    <span>Result</span>
    <div id="result"></div>
</div>

JavaScript

document.getElementById('get-names').onclick = getNamesClick;

function getNamesClick() {
    var chars = document.getElementById('chars').value;
    var names = document.getElementById('names').checked ? 'names' : 
        document.getElementById('animals').checked ? 'animals' : ''
    var result = getNamesByChars(chars, names);
    alert(result);
    console.log(document.getElementById('result'));
    document.getElementById('result').innerHTML = result;
}

function getNamesByChars(chars, names) {
    var result = '';
    charsArray = chars.split(' ');
    for (var i = 0; i < charsArray.length; i++) {
        var values = data[names][charsArray[i]];
        for (var j = 0; j < values.length; j++) {
            if (result != '')
                result += ' ';
            result += values[j];
        }
    }
    return result;
}

var data = {
    'names': {
        'a': [ 'Andrew', 'Allison' ],
        'b': [ 'Bob', 'Barry' ],
        'c': [ 'Cheryl', 'Carol' ],
        'd': [ 'Daniel', 'Danny' ],
        'e': [ 'Eddie', 'Emma' ],
        'f': [ 'Frank', 'Flo' ],
        'g': [ 'Greg', 'Grant' ],
        'h': [ 'Holly' ],
        'i': [ 'Ian' ],
        'j': [ 'John' ],
        'k': [ 'Kaylie' ],
        'l': [ 'Liam' ],
        'm': [ 'Mary' ],
        'n': [ 'Ned' ],
        'o': [ 'Oliver' ],
        'p': [ 'Peter' ],
        'q': [ 'Quentin' ],
        'r': [ 'Ryan' ],
        's': [ 'Sarah' ],
        't': [ 'Tom' ],
        'u': [ 'Ualani' ],
        'v': [ 'Victor' ],
        'w': [ 'Will' ],
        'x': [ 'Xan' ],
        'y': [ 'Yvette' ],
        'z': [ 'Zoe' ]
    },
    'animals': {
        'd': [ 'Dog', 'Dolphin' ],
        'e': [ 'Elephant' ]
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.