JSFiddle - React, Tailwind, and code Playground

by Jonathan McGlone

JavaScript

// Crockford's JS: The Good Parts

// Chapter Four Continued

// Augmenting Types
// Like methods can be available to all objects, so can functions,
// arrays, strings, numbers, regular expressions, and booleans.

Function.prototype.method = function (name, func) {
    this.prototype[name] = func;
    return this;
};

// By augmenting Function.prototype with a method method, we no longer
// have to type the name of the prototype property. That bit of ugliness is now
// hidden.

Number.method('integer', function () {
    return Math[this < 0 ? 'ceil' : 'floor'](this);
});

// window.alert((-10 / 3).integer());

// Here's a method that removes space from the ends of strings:

String.method('trim', function() {
    return this.replace(/^\s+|\s+$/g, '');
});

// window.alert('"' + "   neat    ".trim() + '"');


// Recursion
// A recursive function is a function that calls itself
// It is a technique where a problem is divided into a set
// of similar subproblems, calling itself to solve subproblems

// Towers of Hanoi Recursion Function

var hanoi = function hanoi (disc, src, aux, dst) {
    if (disc > 0) {
        hanoi(disc - 1, src, dst, aux);
        window.alert('Move disc ' + disc + ' from ' + src + ' to ' + dst);
        hanoi(disc - 1, aux, src, dst);
    }
};
hanoi(3, 'Src', 'Aux', 'Dst');

// the function is passed the number of the disc it is to move
// and the three posts it is to use.
// When it calls itself, recursively, it is to deal with the disc
// that is above the disc it is currently working on.
// Eventually, it will be called with a nonexistent disc number
// which in that case it does nothing. 

// Recursive functions can be very effective in manipulating tree structures
// such as the browser's DOM.