Search code examples
javascriptrecursionmutual-recursion

How to make mutually recursive structures in Javascript?


I was wondering if it is possible to have mutually recursive objects in Javascript and, if so, how?

Goal:

I want to have three objects:

  1. One that represents Boolean type with two values True and False
  2. One that represents a True object of Boolean type
  3. One that represents a False object of Boolean type

The trick is that I want to ask the True object its type and I should get back Boolean object and I want to ask a Boolean object its values and I should get back 2 objects: the True object and the False object.

But it should be totally be mutually recursive in the sense that I get something like this (though it doesn't necessarily have to be exactly like this):

True 
// {name : "True", type : [Object object]}

False
// {name : "False", type : [Object object]}

Boolean 
// {name : "Boolean", values : [Object object]}

Boolean.values  
// {True: [Object object], False: [Object object]}

True.type
// {name : "Boolean", values : [Object object]}

False.type
// {name : "Boolean", values : [Object object]}

Boolean.values.True 
// {name : "True", type: [Object object]}

Boolean.values.True.type 
// {name : "Boolean", values : [Object object]}

Boolean.values.True.type.values 
// {True : [Object object], False: [Object object]}

and so on...

If it helps, they should satisfy the properties that:

Boolean === Boolean.values.True.type 
Boolean === Boolean.values.True.type.values.True.type

True === Boolean.values.True
True === True.type.values.True.type.values.True.type.values.True

False === Boolean.values.False
False === True.type.values.False

and the ability to do this should be infinite

Note

These could be functions instead of objects. And the calls don't have to be exactly like this.


Solution

  • Here you go:

    //Define the top level objects but avoid recursion
    var True = {};
    var False = {};
    var Boolean = {
        values: {
            True: True,
            False: False
        }
    };
    
    //Create the recursion
    True.type = Boolean;
    False.type = Boolean;