HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

JavaScript library for Math, String, Array, canvas and location extensions

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
extensionsjavascriptarraymathforlibraryandstringcanvaslocation

Problem

I just wanted to gather your opinion on my little JavaScript library. It features Math, String, Array, canvas and location extensions, as well as some useful animation and timing classes I came up with:

```
/ ====================== /
/ ======= Math ========= /
/ ====================== /

// Random number
Math.rand = function(min, max, float) {
var random = Math.random() * (max-min) + min;
return float ? random : Math.round(random);
};

// Random number with seed (not fully functional)
Math.srand = function(seed, min, max, float) {
var code = 0;
for (var i = 0, l = seed.length; i 1) { code/= 10; }

var mod = code;
var MAX_INT = Math.pow(2,32) - 1;
var min = min != null ? min : -MAX_INT;
var max = max != null ? max : MAX_INT;
var random = mod * (max-min) + min;

return float ? random : Math.round(random);
};

// 3.141592653589793 -> 180°
Math.toDegrees = function(angle) {
return angle * (180 / Math.PI);
};

// 180° -> 3.141592653589793
Math.toRadians = function(angle) {
return angle * (Math.PI / 180);
};

/ ====================== /
/ ======= String ======= /
/ ====================== /

// string -> String
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};

// "test".charAt(2, "oa") -> "toast"
String.prototype.charAt = function(index, replacement) {
if (replacement == null) { return this.substr(index, 1); }
else { return this.substr(0, index-1) + replacement + this.substr(index); }
};

/ ====================== /
/ ======= Array ======== /
/ ====================== /

// Compares values to an array object and returns the index
Array.prototype.compare = function(values) {
for (var i = 0, l = this.length; i = end) { progress = this.reverse ? 0 : 1; }

return progress;
};

this.reset = function() {
if (this.auto_reverse) { this.reverse = this.reverse ? false : true; }

this.timeout = this.callback ? set

Solution

Here are some tips.

1)

Avoid using java keywords. In Math.rand, there is a variable called float.
Try calling it toFloat.

2)

It's best not to browser sniff. Detect for features instead.

Old Code:

function createRequestObject() {

    var request, browser = navigator.appName;

    if (browser == "Microsoft Internet Explorer")
    { request = new ActiveXObject("Microsoft.XMLHTTP"); }
    else
    { request = new XMLHttpRequest(); }

    return request;
}


New Code:

function createRequestObject() {
    var request;
    if (ActiveXObject) {
        request = new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        request = new XMLHttpRequest();
    }
    return request;
}


3)

Try not to repeat yourself.

Old Code:

CanvasRenderingContext2D.prototype.strokeRect = function(x, y, w, h, r1, r2, r3, r4) {
    if (r1 == null) {    
        this.beginPath();
        //...
        this.closePath();
        this.stroke();
    } else {
        //...
        this.beginPath();
        //...
        this.closePath();
        this.stroke();
    }
};


New Code:

CanvasRenderingContext2D.prototype.strokeRect = function(x, y, w, h, r1, r2, r3, r4) {
    this.beginPath();
    if (r1 == null) {    
        this.moveTo(x, y);
        //...
    } else {
        //...
    }
    this.closePath();
    this.stroke();
};


4)

Make functions as small as possible. Try adding functions to the prototype instead of creating them inside the constructor.

Old Code:

var Loop = function(callback, fps) {
// ...
  this.start = function() {

        // Timeout is used to specify a framerate
        this.request = setTimeout(function() {
            requestAnimFrame(function() {
                _this.start();
                _this.delta = (+new Date - _this.lastTime) / (1000 / _this.fps);
                _this.real_fps = Math.round((1 + (1-_this.delta))*_this.fps);
                _this.callback();
                _this.lastTime = +new Date;
            });
        }, 1000 / this.fps);
    };

//...
};


New Code:

Loop.prototype.start = function () {
    // Timeout is used to specify a framerate
            var _this = this;
    this.request = setTimeout(function () {
            requestAnimFrame(function () {
                _this.start();
                _this.delta = (+new Date() - _this.lastTime) / (1000 / _this.fps);
                _this.real_fps = Math.round((1 + (1 - _this.delta)) * _this.fps);
                _this.callback();
                _this.lastTime = +new Date();
            });
        }, 1000 / this.fps);
};


5)

Rename String.prototype.charAt to String.prototype.replaceByIndex

6)

this.fps = fps ? fps : 60; is the same as this.fps = fps || 60;

Code Snippets

function createRequestObject() {

    var request, browser = navigator.appName;

    if (browser == "Microsoft Internet Explorer")
    { request = new ActiveXObject("Microsoft.XMLHTTP"); }
    else
    { request = new XMLHttpRequest(); }

    return request;
}
function createRequestObject() {
    var request;
    if (ActiveXObject) {
        request = new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        request = new XMLHttpRequest();
    }
    return request;
}
CanvasRenderingContext2D.prototype.strokeRect = function(x, y, w, h, r1, r2, r3, r4) {
    if (r1 == null) {    
        this.beginPath();
        //...
        this.closePath();
        this.stroke();
    } else {
        //...
        this.beginPath();
        //...
        this.closePath();
        this.stroke();
    }
};
CanvasRenderingContext2D.prototype.strokeRect = function(x, y, w, h, r1, r2, r3, r4) {
    this.beginPath();
    if (r1 == null) {    
        this.moveTo(x, y);
        //...
    } else {
        //...
    }
    this.closePath();
    this.stroke();
};
var Loop = function(callback, fps) {
// ...
  this.start = function() {

        // Timeout is used to specify a framerate
        this.request = setTimeout(function() {
            requestAnimFrame(function() {
                _this.start();
                _this.delta = (+new Date - _this.lastTime) / (1000 / _this.fps);
                _this.real_fps = Math.round((1 + (1-_this.delta))*_this.fps);
                _this.callback();
                _this.lastTime = +new Date;
            });
        }, 1000 / this.fps);
    };

//...
};

Context

StackExchange Code Review Q#15492, answer score: 6

Revisions (0)

No revisions yet.