repl.it
@anonymous/

CylindricalTiredAngwantibo

JavaScript

No description

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/* Create a function that does all the boilerplate work for inheritance */
Function.prototype.inherit = function(base) {
    this.prototype = new base;
    this.prototype.constructor = this;
    this.prototype.parent = base.prototype;
}

/* Derive some classes */
function List() {}
List.inherit(Array);

function Lambda() {}
Lambda.inherit(Function);

function Integer() {}
Integer.inherit(Number);

function Natural() {}
Natural.inherit(Integer);

function Currency() {}
Currency.inherit(Number);

/* List of classes to graph (include the root class, Object) */
var a = [Object, String, Number, Array, Function, List, Lambda, Integer, Natural, Currency];

/* Expand list of classes into list of objects which refer to classes */
a = a.map(
        function (c) {
            return { 'c': c, 'ancestors': [], 'descendants': [] };
        }
    );

/* Build graph edges */
for (var i = 0; i < a.length; i++) {
    var A = a[i];
    for (var j = 0; j < a.length; j++) {
        if (i == j)
            continue;
        var B = a[j];
        if ((new A.c()) instanceof B.c)
            A.ancestors.push(B);
        if ((new B.c()) instanceof A.c)
            A.descendants.push(B);
    }
}

/* Sort graph so highest level node is first (assuming root node is present)
   Cheap and dirty way that won't work for forests, but thats why we include
   the root node */
a = a.sort(function (p, q) { return p.ancestors.length - q.ancestors.length; });

/* Add list indices to graph vertices */
for (var i = 0; i < a.length; i++)
    a[i].index = i;

/* Get immediate parent of each node */
a = a.map(
    function (item) {
        item.parent = item.ancestors.reduce(
            function (state, anc) {
                if (!state || anc.index > state.index)
                    return anc;
            },
            null);
        return item;
    });

/* Print graph (as tree, since we avoided the mess of multiple inheritance) */
function print(item, ind, last) {
    ind += "  ";
    console.log(ind + item.c.name);
    for (var i = 0; i < item.descendants.length; i++)
        if (item.descendants[i].parent == item)
            print(item.descendants[i], ind, i == item.descendants.length - 1);
}

print(a[0], "", true);
Native Browser JavaScript
?