Branch Statement Optimization — Strategy Pattern
Published: 2019-01-25
Learn more
animate({width: '200px'}, 1000, 'linear')Pattern example
// Form regex validation strategy object
var Inputstrategy = function() {
var strategy = {
// whether empty
notNull: function(value) {
return /\s+/.test(value) ? 'Please enter content' : ''
},
// whether it’s a number
number: function(value) {
return /^[0-9]+(\.[0-9]+)?$/.test(value) ? '' : 'Please enter a number'
},
// whether it’s a local phone number
phone: function(value) {
return /^\d{3}\-\d{8}$|^\d{4}\-\d{7}$/.test(value) ? '' : 'Please enter a valid phone number'
}
}
return {
// validate type algorithm value form value
check: function (type, value) {
// trim leading and trailing whitespace
value = value.replace(/^\s+|\s+$/g, '');
return strategy[type] ? strategy[type](value) : 'No detection method for this type'
},
// add strategy
addStrategy: function (type, fn) {
strategy[type] = fn
}
}
}()Summary
Last updated