Home > OS >  How to reuse conditional check for each function?
How to reuse conditional check for each function?

Time:05-31

I have many functions example like this

function update() {
  if (isAdminUser()) {
    return false;
  }
  ...
}
function get() {
  if (isAdminUser()) {
    return false;
  }
  ...
}
...

is there any possible way to have the conditional statement

 if (isAdminUser()) {
   return false;
 })

written once and run by itself at the beginning of each function. I'm using javascript

CodePudding user response:

If you use TypeScript try decorators.

Docs: https://www.typescriptlang.org/docs/handbook/decorators.html#decorators

CodePudding user response:

maybe you can define a function that can accept another function as an argument and returns false if that function (i.e isAdminUser in your code snippet) returns true

const checkUser = func => func() && false

then the function can be used like:

function update() {
    if (checkUser(isAdminUser)) {
        // update() logic will only run if user is not admin
    }

}
function get() {
   if (checkUser(isAdminUser)) {
      // get() logic will only run if user is not admin   
   }
 }

CodePudding user response:

You could use a higher order function to encapsulate the logic needed to run before a specific function is run. Higher order functions take functions as parameters, therefore a possible solution to your problem could look like this:

function withIsAdminUser(callback) {
  return function() { 
    if (isAdminUser()) {
      return false;
    }
    return callback();
  }
}

function getRaw() {
  // Do something here, this whole function could also be inlined
}
const get = withIsAdminUser(getRaw);
  • Related