Skip to content

Instantly share code, notes, and snippets.

@Pikuseru
Created October 23, 2016 13:21
Show Gist options
  • Save Pikuseru/d16edd97dbbe2f7db58961c90ef341bd to your computer and use it in GitHub Desktop.
Save Pikuseru/d16edd97dbbe2f7db58961c90ef341bd to your computer and use it in GitHub Desktop.
Decorators
<!DOCTYPE html>
<html lang="en">
<head>
<title>bunkum</title>
<script src="bunkum.js"></script>
</head>
<body>
</body>
</html>
//
// validation decorator functions
//
var Validators = {
number: function (fn) {
return function (parameter) {
if (typeof parameter === 'number') {
fn(parameter);
} else {
throw parameter + ' is not a number';
}
}
},
positiveNumber: function (fn) {
return Validators.number(function (parameter) {
if (parameter >= 0) {
fn(parameter);
} else {
throw parameter + ' is not positive'
}
})
}
};
//
// logging decorator function
//
var Logging = {
mode: '',
log: function (fn) {
return function () {
try {
fn.apply(null, arguments);
}
catch (e) {
if (Logging.mode === 'errors') {
console.error(e);
}
throw e;
}
}
}
};
//
// decorate the application operations we want to expose
//
var BuildObject = function () {
return {
doSomething1: Logging.log(Validators.number(function (parameter) {
console.log('doSomething1 with ' + parameter);
})),
doSomething2: Logging.log(Validators.positiveNumber(function (parameter) {
console.log('doSomething2 with ' + parameter);
}))
};
};
var test = function () {
var object = BuildObject();
try {
object.doSomething1(5);
} catch (e) {
}
try {
object.doSomething1('foo');
} catch (e) {
}
try {
object.doSomething2(1);
} catch (e) {
}
try {
object.doSomething2(-1);
} catch (e) {
}
};
console.log('logging off');
test();
console.log('logging errors');
Logging.mode = 'errors';
test();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment