Monday, 18 July 2011

javascript code samples

Simple examples
A simple recursive function:
function factorial(n) {
    if (n == 0) {
        return 1;
    }
    return n * factorial(n - 1);
}
A simple personalised greeting script:
var name = prompt("What is your name?");
alert("Welcome " + name);
Anonymous function (or lambda) syntax:
function add(i, j) {
    var addLambda = function(x, y) {
        return x + y;
    };

    return addLambda(i, j);
}
function displayClosure() {
    var inc = makeIncreaser(1);

    inc(); // returns 1
    inc(); // returns 2
    inc(); // returns 3
}

function makeIncreaser(init) {
    var count = init;
    return function() {
        return count++;
    };
}




Variadic function demonstration. This will alert with 1 then 2 then 3. arguments is a special variable.
function unlimitedArgs() {
    for (var i = 0; i < arguments.length; ++i) {
        alert(arguments[i]);
    }
}

unlimitedArgs(1, 2, 3);

More advanced example
This sample code showcases various JavaScript features.
/* Finds the lowest common multiple of two numbers */
function LCMCalculator(x, y) { // constructor function
    var checkInt = function (x) { // inner function
        if (x % 1 !== 0) {
            throw new TypeError(x + "is not an integer"); // throw an exception
        }
        return x;
    };
    this.a = checkInt(x)
    // ^ semicolons are optional
    this.b = checkInt(y);
}
// The prototype of object instances created by a constructor is
// that constructor's "prototype" property.
LCMCalculator.prototype = { // object literal
    constructor: LCMCalculator, // when reassigning a prototype, set the constructor property appropriately
    gcd: function () { // method that calculates the greatest common divisor
        // Euclidean algorithm:
        var a = Math.abs(this.a), b = Math.abs(this.b), t;
        if (a < b) {
            // swap variables
            t = b;
            b = a;
            a = t;
        }
        while (b !== 0) {
            t = b;
            b = a % b;
            a = t;
        }
        // Only need to calculate GCD once, so "redefine" this method.
        // (Actually not redefinition - it's defined on the instance itself,
        // so that this.gcd refers to this "redefinition" instead of LCMCalculator.prototype.gcd.)
        // Also, 'gcd' == "gcd", this['gcd'] == this.gcd
        this['gcd'] = function() {
            return a;
        };
        return a;
    },
    "lcm"/* can use strings here */: function() {
        // Variable names don't collide with object properties, e.g. |lcm| is not |this.lcm|.
        // not using |this.a * this.b| to avoid FP precision issues
        var lcm = this.a / this.gcd() * this.b;
        // Only need to calculate lcm once, so "redefine" this method.
        this.lcm = function() {
            return lcm;
        };

        return lcm;
    },
    toString: function () {
        return "LCMCalculator: a = " + this.a + ", b = " + this.b;
    }
};

// Note: Array's map() and forEach() are defined in JavaScript 1.6.
// They are used here to demonstrate JavaScript's inherent functional nature.

[[25, 55],[21, 56],[22, 58],[28, 56]].map(function(pair) { // array literal + mapping function
    return new LCMCalculator(pair[0], pair[1]);
}).sort(function(a, b) { // sort with this comparative function
    return a.lcm() - b.lcm();
}).forEach(function(obj) {
    document.write(obj + ", gcd = " + obj.gcd() + ", lcm = " + obj.lcm() + "<br>");
});
The following output should be displayed in the browser window.
LCMCalculator: a = 28, b = 56, gcd = 28, lcm = 56
LCMCalculator: a = 21, b = 56, gcd = 7, lcm = 168
LCMCalculator: a = 25, b = 55, gcd = 5, lcm = 275
LCMCalculator: a = 22, b = 58, gcd = 2, lcm = 638
This obfuscated example writes "Hello World"; it is made to be copy/pasted into the web address bar.
javascript:var AZ=new Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " "); var az=new Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", " "); document.write(AZ[7],az[4],az[11],az[11],az[14],AZ[26],AZ[22],az[14],az[17],az[11],az[3])
This is the same code adapted to html markup.
<script type="text/javascript">
//Creates the capital letters
var AZ=new Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " ");
//Creates the lowercase letters
var az=new Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", " ");
//writes the text based on AZ and az
document.write(AZ[7],az[4],az[11],az[11],az[14],AZ[26],AZ[22],az[14],az[17],az[11],az[3])
</script>

No comments:

Post a Comment