JavaScript对象当map使

一个转换函数:

getIconURL: function(content) {
    if (typeof content !== 'string') {
        return undefined;
    }
    switch (content) {
    case 'stopped':
        return 'resources/icons/circle_red_l.png';
    case 'running':
        return 'resources/icons/circle_green_l.png';
    case 'pending':
        return 'resources/icons/circle_orange_l.png';
    case 'shutting-down':
        return 'resources/icons/circle_orange_l.png';
    case 'stopping':
        return 'resources/icons/circle_orange_l.png';
    case 'available':
        return 'resources/icons/disconnect.png';
    case 'error':
        return 'resources/icons/delete.png';
    case 'us-east-1':
        return 'resources/icons/flag_us.png';
    case 'us-west-1':
        return 'resources/icons/flag_us.png';
    case 'us-west-2':
        return 'resources/icons/flag_us.png';
    case 'ap-northeast-1':
        return 'resources/icons/flag_jp.png';
    case 'ap-southeast-1':
        return 'resources/icons/flag_sg.png';
    case 'eu-west-1':
        return 'resources/icons/flag_eu.png';
    case 'sa-east-1':
        return 'resources/icons/flag_br.png';
    case 'valid':
        return 'resources/icons/accept.png';
    case 'invalid':
        return 'resources/icons/delete.png';
    default:
        return undefined;
    }
}

新的分支越加越多,就越觉得效率有问题,而且这个函数经常被调用

想使用map来代替switch,但又不想用ExtJS的HashMap
于是把JavaScript的对象当map使,还是非常好用的
速度没测过,但在分支特别多的情况下应该要快上很多

/**
 * @author kuyur
 */

Ext.define('myproject.util', {
	statics: {
		map: {
			'stopped': 'resources/icons/circle_red_l.png',
			'running': 'resources/icons/circle_green_l.png',
			'pending': 'resources/icons/circle_orange_l.png',
			'shutting-down': 'resources/icons/circle_orange_l.png',
			'stopping': 'resources/icons/circle_orange_l.png',
			'available': 'resources/icons/disconnect.png',
			'error': 'resources/icons/delete.png',
			'us-east-1': 'resources/icons/flag_us.png',
			'us-west-1': 'resources/icons/flag_us.png',
			'us-west-2': 'resources/icons/flag_us.png',
			'ap-northeast-1': 'resources/icons/flag_jp.png',
			'ap-southeast-1': 'resources/icons/flag_sg.png',
			'eu-west-1': 'resources/icons/flag_eu.png',
			'sa-east-1': 'resources/icons/flag_br.png',
			'valid': 'resources/icons/accept.png',
			'invalid': 'resources/icons/delete.png'
		},
		getIconURL: function(content) {
			if (typeof content !== 'string') {
				return undefined;
			}
			return myproject.util.map[content];
		},
		...
	}
});
2012年8月2日 | 归档于 技术, 程序
本文目前尚无任何评论.

发表评论

XHTML: 您可以使用这些标签: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>
:wink: :-| :-x :twisted: :) 8-O :( :roll: :-P :oops: :-o :mrgreen: :lol: :idea: :-D :evil: :cry: 8) :arrow: :-? :?: :!: