Skip to content

Instantly share code, notes, and snippets.

@ishiduca
Created January 15, 2016 03:11
Show Gist options
  • Save ishiduca/f044dd0da9624a6540b3 to your computer and use it in GitHub Desktop.
Save ishiduca/f044dd0da9624a6540b3 to your computer and use it in GitHub Desktop.
Re: Javascriptでデザインパターン (その7: Chain of Responsibility) ref: http://qiita.com/ishiduca/items/592afefb0eb721961f82
function Client () {
this.validators = [].slice.apply(arguments).filter(flt)
}
function flt (validator) {
return 'function' === typeof (validator || {}).request
}
Client.prototype.request = function (input) {
for (var i = 0; i < this.validators.length; i++) {
this.validators[i].request(input)
}
}
var client = new Client(
new TyepCheck
, new MinLengthCheck(min_length)
, new MaxLengthCheck(max_length)
, new MainHandler
)
client.request(foo)
function MainHandler () {}
MainHandler.prototype.request = function (input) {
console.log('validate ok - "%s"', input)
return !0
}
var client = new Client(
new TypeCheck
, new MinLengthCheck(4)
, new MaxLengthCheck(6)
, new MainHandler
)
test()
test('lg')
test('looooog!!')
test('log')
function test (input) {
try {
client.request(input)
} catch (err) {
console.error(err)
}
}
function MaxLengthCheck (max_length) {
this.max_length = max_length
}
MinLengthCheck.prototype.request = function (input) {
if (this.max_length > input)
throw new Error('too long')
return !0
}
function MinLengthCheck (min_length) {
this.min_length = min_length
}
MinLengthCheck.prototype.request = function (input) {
if (this.min_length < input)
throw new Error('too short')
return !0
}
function TypeCheck () {}
TypeCheck.prototype.request = function (input) {
if ('string' !== typeof input)
throw new TypeError('"input" must be "string"')
return !0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment