I have two similiar functions that both require the same parameter checks
function doThis(foo, bar) {
if (foo.length === 0) foo = 'foo';
if (bar.length === 0) bar = 'bar';
foo = encodeURI(foo);
bar = encodeURI(bar);
// ... some other checks and enforcements...
// Output as alert
alert(foo + bar);
}
function doThat(foo, bar) {
if (foo.length === 0) foo = 'foo';
if (bar.length === 0) bar = 'bar';
foo = encodeURI(foo);
bar = encodeURI(bar);
// ... some other checks and enforcements...
// Output on console
console.log(foo + bar);
}
What is a proper way to dry this up? I came up with this:
function paramsCheck(foo, bar) {
if (foo.length === 0) foo = 'foo';
if (bar.length === 0) bar = 'bar';
foo = encodeURI(foo);
bar = encodeURI(bar);
// maybe some other checks and enforcements...
return { foo: foo, bar: bar };
}
function doThis(foo, bar) {
var params = paramsCheck(foo, bar);
// Output
alert(params.foo + params.bar);
}
function doThat(foo, bar) {
var params = paramsCheck(foo, bar);
// Output
console.log(params.foo + params.bar);
}
But I'm not really happy with it. I would rather like pass the parameters as references to paramsCheck(), so I can directly modify them instead of returning a new object.