Created
June 6, 2018 07:28
-
-
Save Lxxyx/d16829b7936f7e2043855b47b117c007 to your computer and use it in GitHub Desktop.
重构例子
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ================你写的================== | |
/** | |
* | |
* @param {String, Object} message | |
* @param {Enum} position | |
*/ | |
const showToast = (message, position = 'middle') => { | |
let iconClass = ['nbsicon'] | |
// 根据message类型处理iconCLass | |
let msg = '' | |
typeof message !== 'undefined' ? '' : iconClass.push('nbs-error-s') | |
if (typeof message === 'undefined') { | |
iconClass.push('nbs-error-s') | |
} else if (typeof message === 'object') { | |
msg = message.message | |
if (message.status === 1) { | |
iconClass.push('nbs-success-s') | |
} else { | |
iconClass.push('nbs-error-s') | |
} | |
} else if (typeof message === 'string') { | |
msg = message | |
if (message.match(/[Ss]ucce/g) || message.match(/成功/g)) { | |
iconClass.push('nbs-success-s') | |
} else { | |
iconClass.push('nbs-error-s') | |
} | |
} else { | |
iconClass.push('nbs-error-s') | |
} | |
Toast({ | |
message: msg, | |
className: 'nbs-toast', | |
iconClass: iconClass.join(' '), | |
position: position, | |
duration: 3000 | |
}) | |
} | |
// ===============我重构的================= | |
function showToast(message, position = 'middle') { | |
const iconClass = getClassName(message) | |
const content = getMessageContent(message) | |
Toast({ | |
message: content, | |
className: 'nbs-toast', | |
iconClass, | |
position, | |
duration: 3000 | |
}) | |
} | |
const ERROR = 'nbs-error-s' | |
const SUCCESS = 'nbs-success-s' | |
const DEFAULT = 'nbsicon' | |
const REQUEST_SUCCESS = 1 | |
function getClassName(message) { | |
const className = ['nbsicon'] | |
let state = ERROR | |
const type = typeof message | |
switch (type) { | |
case 'undefined': | |
state = ERROR | |
break; | |
case 'string': | |
const re = /[Ss]ucce|成功/g | |
state = re.test(message) ? SUCCESS : ERROR | |
break; | |
case 'object': | |
state = msg.status === REQUEST_SUCCESS ? SUCCESS : ERROR | |
break | |
} | |
className.push(state) | |
return className.join(' ') | |
} | |
function getMessageContent(message = '') { | |
if (typeof message === 'object') { | |
return message.message | |
} | |
return message | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
确实。。结构和逻辑都清晰了很多