// 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.
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.