9e2c437fb89b21498e262788e45b20c8

help me produce better code?

var search = 'foo';
var key = null;
switch (search) {
  case: 'foo':
    key = 'toilet';
    break;
  case: 'bar':
    key = 'home';
    break;
  case: 'bat':
    key = 'office';
    break;
}

// key is 'toilet'

Refactorings

No refactoring yet !

Aacfa176a8d73ca75b90b6375151765a

Paul Wilkins

March 16, 2009, March 16, 2009 07:39, permalink

3 ratings. Login to rate!

I hope that a search of bar doesn't result in two different keywords. I've used a different keyword here of 'bat' for the last one instead.

var terms = {
    'foo': 'toilet',
    'bar': 'home',
    'bat': 'office'
}
var search = 'foo';
var key = terms[search];

// key is 'toilet'
F1e3ab214a976a39cfd713bc93deb10f

Tj Holowaychuk

March 18, 2009, March 18, 2009 01:01, permalink

No rating. Login to rate!
function search(term) {
  return {
    foo  : 'bar',
    bar  : 'foo',
    rawr : 'blah',
  }[term] || null
}

print(search('foo')) 
// => bar

print(search('whatever')) 
// => null
87592c76b8b913ea464a1546aeb011d5

AGuerren

March 20, 2009, March 20, 2009 05:19, permalink

No rating. Login to rate!

A switch statement probably doesn't need much cleaning up seeing as how the interpreter will treat it as a lookup table anyway. In terms of performance I'd wager it'd beat any of these other toys solutions hands down but at least you can have some fun with it!

var search = (function gen_search(list) { 
    return function( term ) {  
        return (list[term] || null); 
    }
})({ foo : 'bar', bar : 'foo', rawr : 'blah' });
alert( search("toilet") );
alert( search("rawr") );
alert( search.toString() );

var other_search = gen_search( {foo: 'man'} );
alert(other_search( "foo" ));
F1e3ab214a976a39cfd713bc93deb10f

Tj Holowaychuk

March 20, 2009, March 20, 2009 06:17, permalink

No rating. Login to rate!

You basically just did what I did ... just with some really unnecessary anonymous functions. Granted if this is something he wishes to re-use it misewell be a generator. Style / usability > performance

D41d8cd98f00b204e9800998ecf8427e

AGuerren

March 24, 2009, March 24, 2009 14:56, permalink

No rating. Login to rate!

Ease up, you're right. It is "basically" what you'd done just as what you'd done is "basically" what the previous poster had done. The problem was fairly simple anyway and this offers a solution that can be re-used without the need for a hard-coded list. As for performance - as you'd noted, the generated code is the same.

0503492f1cc60e41f25a20188a63d60a

vipin cherukara

September 15, 2009, September 15, 2009 11:30, permalink

No rating. Login to rate!

For javascript tutorials , examples and sample codes
http://javascriptfactory.blogspot.com/

Your refactoring





Format Copy from initial code

or Cancel