用hash表 来替换if else

    在写处理短信的时候,要根据短信的内容来判断是报名短信和竞价短信时候,要到一些 if else, 可以用hash表的形式来替换掉这些代码。

 if(message.content.substring(0, 2).toUpperCase() == "BM") {
        process_activity_sign_up_message()
    } else if (message.content.substring(0, 2).toUpperCase() == "JJ") {
        process_bid_sign_up_message()
    } else {
        prompt_message_format()
    }

   下面用hash的形式来替换一下:

fore_two_string = message.content.substring(0, 2).toUpperCase()
  judge_message()
function judge_message() {
    var judge_message = {
        BM: function() {
            process_activity_sign_up_message()
        },

        JJ: function() {
            process_bid_sign_up_message()
        }
    }

    if(judge_message[fore_two_string]) {
        judge_message[fore_two_string]()
        return
    }
    prompt_message_format()
}

    根据活动状态来处理短信:

judge_activity_status()

function judge_activity_status() {

    var status = ActivityInfo.get_starting_activity()
    if(status == "un_start") {
        console.log("活动报名还未开始, 请稍后再试。")
        return
    }

    if(status == "start") {
        process_message_when_activity_status_start()
        return
    }
    
    if(status == "end") {
        console.log("抱歉,活动报名已经结束。")
    }

    用hash 来替换:

judge_activity_status()

function judge_activity_status() {
    var judge_activity_status = {
        un_start: function() {
            console.log("活动报名还未开始, 请稍后再试。")
        },

        end: function() {
            console.log("抱歉,活动报名已经结束。")
        },

        start: function() {
            process_message_when_activity_status_start()
        }
    }
   judge_activity_status[ActivityInfo.get_starting_activity().status]()
}

    不知道hash表的key时,如何取value值。在统计竞价各价钱的人数时:

var group_bid_sign_up_infos_by_price = _.groupBy(bid_sign_up_infos, function(bid_sign_up_info) {
        return bid_sign_up_info.price
    }) 
var price_counts = [ ]
_.map(group_bid_sign_up_infos_by_price, function(value, key) {
    price_counts.push({price: key, count: value.length})
})
return price_counts

    用Underscope的_.groupBy来对竞价进行按price分组,再_.map来遍历分组后产生的hash表,然后对它进行新的数据封装。也可以用

for(key in group_bid_sign_up_infos_by_price) {
    price_counts.push({price: key, count: group_bid_sign_up_infos_by_price[key].length})
}

你可能感兴趣的:(js,hash,if-else)