js优雅的写法1

js优雅的写法

点击switch case

/**
* 按钮点击事件
* @param {number} status 活动状态: 1进行中 2失败 3已结束 4已取消
*/
const onButtonClick = (status) => {
    switch(status) {
        case 1:
          sendLog('processing')
          break;
        case 2:
          sendLog('fail')
          break;
        case 3:
          sendLog('shibai')
          break;
        case 4:
          sendLog('cenceled')
          break;
        default:
          sendLog('cenceled')
          break;
    }
}

const  actions = new Map([
    [1, ['processing']],
    [2, ['fail']],
    [3, ['shibai']],
    [4, ['cenceled']],
    ['default', ['other']]
])
consg onButtonClick = (status) => {
    let action = actions[status] || actions['default']
    sendLog(action[0])
}
条件升级,角色 + 条件
/**
* 两个权限A B
* @param {string} identity 身份标识:guest客人 master管理员
* @param {number} status 状态: 1xx 2xx 3xx
*/
const onButtonClick = (status, identity) => {
    if (identity == 'guest') {
        if (status == 1) { 
            // do sth
        }else if (status == 2) {
            // do sth
        }else if (status == 3) {
            // do sth
        } else {
            // do sth
        }
    } else {
        if (status == 1) { 
            // do sth
        }else if (status == 2) {
            // do sth
        }else if (status == 3) {
            // do sth
        } else {
            // do sth
        }
    }
}
// 优化
const actions = new Map([
    ['guest_1', () => { /* do sth */ }],
    ['guest_2', () => { /* do sth */ }],
    ['guest_3', () => { /* do sth */ }],
    ['guest_0', () => { /* do sth */ }],
    ['master_1', () => { /* do sth */ }],
    ['master_2', () => { /* do sth */ }],
    ['master_3', () => { /* do sth */ }],
    ['master_0', () => { /* do sth */ }],
])
const onButtonClick = (status, identity) => {
    let action = actions.get(`${identity}_${status}`) || actions.get(`${identity}_0`)
    action.call(this)
}

// 继续优化
const actions = () => {
    const funA = () => {/* do sth */}
    const funB = () => {/* do sth */}
    const funElse = () => {/* do sth */}
    return new Map([
        [/^guest_[1-3]$/, funA],
        [/^mastet_[1-3]$/, funB],
        [/^guest_0|master_0$/, funElse],
        // [/^guest_.*$/, funElse],
    ])
}
const onButtonClick = (status, identity) => {
    let action = actions.get(`${identity}_${status}`) || actions.get(`${identity}_0`)
    action.call(this)
}

你可能感兴趣的:(前端开发,es6,javascript)