DEV Community

Discussion on: If - procedural, functional, object-oriented

Collapse
 
stereobooster profile image
stereobooster • Edited
  1. those are just educational examples, most of the time people would use "procedural" form
  2. there is no native support for it in JS so it's just imitation. We will need some function which will convert from native boolean to ours booleans
// Implementation:
const True = (x) => (y) => x;
const False = (x) => (y) => y;
const If = (condition, thenAction, elseAction) => {
  const action = condition(thenAction)(elseAction);
  return action();
}
// Usage:
const convertNativeBoolean = (b) => b === true ? True : False;
const condition = convertNativeBoolean(Math.random() > 0.5);
const result = If(condition, () => "More" , () => "Less");
console.log(result);
// Implementation:
class TrueClass {
  Then(callBack) {
    callBack.call()
    return this
  }
  Else(callBack) {
    return this
  }
}
class FalseClass {
  Then(callBack){
    return this
  }
  Else(callBack){
    callBack.call()
    return this
  }
}
const True = new TrueClass();
const False = new FalseClass();
// Usage:
const convertNativeBoolean = (b) => b === true ? True : False;
const condition = convertNativeBoolean(Math.random() > 0.5);
condition.Then(() => console.log("More")).Else(() => console.log("Less"))

Or imagine any function which would return our predefined values True or False.

Collapse
 
dalmo profile image
Dalmo Mendonça

Awesome, thanks.

The conversion was the tricky part... looks obvious now that you showed it.

Thread Thread
 
stereobooster profile image
stereobooster • Edited

Yeah... They idea is to imagine language wehere instead of true/false (0/1) they use True/False (those which I provided). It is hard to wrap head around in JS. But I have series of posts about creating a language, in this language we can:

  • 1 - implement "procedural" if
  • 2 - remove "procedural" if and implement functional if

This should be more clear.