Definition 1.
Use a set of “algorithms” that encapsulate them and can call each other.
(Note that the algorithm can be a simple key-value relationship, usually optimizing code with method calls + arguments)
2. Problem solving:
2.1 Common judgment of conditions
/ / before optimization
let operateName = ' '
if(operateKey === "add"){
operateName = 'new'
}else if(operateKey === "edit"){
operateName = 'change'
}else if(operateKey === "view"){
operateName = 'look at'
}
/ / after optimization
function getOperateName(key){
const array = [['add'.'new'], ['edit'.'change'], ['view'.'look at']]
const strategyMap = new Map(array)
return strategyMap.get(key) // Get the corresponding value from the key-value relationship
}
getOperateName("add")
/ / output
/ / new
Copy the code
2.2 Form Verification
let loginFrom = document.getElementId("loginFrom")
loginFrom.onsubmit = function (e) {
const username = document.getElementId("username")
const pwd = document.getElementId("pwd")
const mobile = document.getElementId("mobile")
if (username === null || username === ' ') {
alert("User information is empty.")
return false
}
if (pwd === null || pwd === ' ') {
alert("Password cannot be empty.")
return false
}
if (!/ (a ^ 1 [3 4 5 7 | | | | 8] [0-9] {9} $) /.test(mobile)) {
alert("Wrong phone message.")
return false}}// Code optimization
let strategy = {
isEmpty: function(value,msg){
if (value === null || value === ' ') {
return errorMsg
}
},
isMobile: function (value, errorMsg) { // Mobile phone number format
if (!/ (a ^ 1 [3 4 5 7 | | | | 8] [0-9] {9} $) /.test(value)) {
return errorMsg
}
}
}
let usernameMsg = strategy.isEmpty(username,"User information is empty.")
let pwdMsg = strategy.isEmpty(pwd,"User information is empty")
let pwdMsg = strategy.isEmpty(pwd,"User information is empty")
let mobileMsg = strategy.isEmpty(pwd,"The phone number format is wrong.")
const errorMsg = usernameMsg || pwdMsg || mobileMsg
if(errorMsg) {
alert(errorMsg)
return false
}
Copy the code