Pascal Nardi
Pascal Nardi

Reputation: 101

Boolean test as argument

I would like to have something looking like this

let condition = function(name, cond) {
this.name = name;
this.func = (prop) => {
    if (cond) { 
        return true;
    }
    return false;
}

let snow = new condition("temperature", prop < 0);

I have a temerature value on a separate folder and a function checking if condition.func returns true or false. For example it can't snow if temperature is under 0, this means that I would call the condition.func(temperature) and this would execute the code if (temperature < 0){return true}.
The problem is when I define snow it throws the error that prop is not defined...
I understand this is because I am looking to override a variable not even initialized, but I have no idea of how to implement a boolean test as an argument of a function

Upvotes: 0

Views: 41

Answers (3)

Thijs
Thijs

Reputation: 2351

You need a method to check if the value matches your condition. See below for a possible solution.

let condition = function(name, predicate) {
  this.name = name
  // func will take a single value, the temperate to check
  this.func = (prop) => {
      // Execute the predicate method with the provided value.
      return predicate(prop);
  }
}

/**
 * This method will check your condition, it takes a single value as a param
 */
function snowPredicate(value) {
  // It can only snow when value is less than 0.
  return (value < 0);
}

// Set the condition for snow, pass the predicate method as the check.
let snow = new condition("temperature", snowPredicate)

// Check if it can snow when it is 10 degrees and -1 degrees.
console.log(snow.func(10));
console.log(snow.func(-1));

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386736

You could just hand over the function, without an intermediate function. For the condition, you need a function, like p => p < 0, not just a condition, like prop < 0. This works only hard coded or with eval, as string, but not as parameter.

function Condition (name, cond) {
    this.name = name
    this.func = cond
}

let snow = new Condition("temperature", p => p < 0);

console.log(snow.func(5));
console.log(snow.func(-5));

Upvotes: 1

Suren Srapyan
Suren Srapyan

Reputation: 68675

You need to pass a function or arrow-functionwith an input parameter to your condition and it will be stored in the cond prop. And then when you call func pass a parameter into the func and use the cond reference to call your cond function with that given parameter like cond(prop). Also you can simplify your func function and refer to only cond.

let condition = function(name, cond) {
   this.name = name;
   this.func = cond;
};

let snow = new condition("temperature", prop => prop < 0);

if(snow.func(-2)){
  console.log(`Snowing`);
}

Upvotes: 2

Related Questions