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 !
Paul Wilkins
March 16, 2009, March 16, 2009 07:39, permalink
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'
Tj Holowaychuk
March 18, 2009, March 18, 2009 01:01, permalink
function search(term) {
return {
foo : 'bar',
bar : 'foo',
rawr : 'blah',
}[term] || null
}
print(search('foo'))
// => bar
print(search('whatever'))
// => null
AGuerren
March 20, 2009, March 20, 2009 05:19, permalink
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" ));
Tj Holowaychuk
March 20, 2009, March 20, 2009 06:17, permalink
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
AGuerren
March 24, 2009, March 24, 2009 14:56, permalink
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.
vipin cherukara
September 15, 2009, September 15, 2009 11:30, permalink
For javascript tutorials , examples and sample codes
http://javascriptfactory.blogspot.com/
help me produce better code?