Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Jonas Raoni Soares Silva http://www.jsfromhell.com

« Newer Snippets
Older Snippets »
Showing 1-10 of 21 total  RSS 

Bézier Curve //JavaScript Class


Calculates the points for a bézier curve.

[UPDATED CODE AND HELP CAN BE FOUND HERE]


//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/math/bezier [v1.0]

function Bezier(p0, p1, c0, c1){//v1.0
	var o = this;
	o.x0 = p0.x, o.y0 = p0.y, o.x1 = p1.x, o.y1 = p1.y,
	o.cx0 = c0.x, o.cy0 = c0.y, o.cx1 = c1.x, o.cy1 = c1.y;
};
with({$: Bezier, o: Bezier.prototype}){
	$.point = function(x, y){
		return {x: x, y: y};
	};
	o.getCoordinates = function(t){
		var i = 1 - t, x = t * t, y = i * i, a = x * t,
		b = 3 * x * i, c = 3 * t * y, d = y * i, o = this;
		return Bezier.point(a * o.x0 + b * o.cx0 + c * o.cx1 + d * o.x1,
		a * o.y0 + b * o.cy0 + c * o.cy1 + d * o.y1);
	};
	o.plot = function(c){
		var r, x = (x = this.x0 - this.x1) * x, y = (y = this.y0 - this.y1) * y,
		l = l = Math.ceil(Math.sqrt(x + y)), i = l + 1;
		while(c(this.getCoordinates(r = --i / l), r), i);
	};
}



Usage

var bezier = new Bezier(Bezier.point(0, 50), Bezier.point(100, 20), Bezier.point(50, 0), Bezier.point(50, 50));
bezier.plot(function(p, r){
	document.write("x: ", p.x >> 0, " y: ", p.y >> 0, " at ", (r * 100).toFixed(1), "%<br />");
});

Math Parser //JavaScript Class


This class is able to parse math expressions and also run user defined functions.

On JavaScript there's the "eval" function, that can do such things well, but this code objective was just to give me fun or a new challenge =)~

[UPDATED CODE AND HELP CAN BE FOUND HERE]

Usage:

x = new MathProcessor;
try{alert(x.parse("1+2-(3*4) + medium(2,3) - frac( 2.2231)"));}
catch(e){alert(e);}


It's possible to add more functions to the class, just add them into the "methods" property ;]

Well, that's it :)

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/math-processor [v1.0]

MathProcessor = function(){ //v1.0
    var o = this;
    o.o = {
        "+": function(a, b){ return +a + b; },
        "-": function(a, b){ return a - b; },
        "%": function(a, b){ return a % b; },
        "/": function(a, b){ return a / b; },
        "*": function(a, b){ return a * b; },
        "^": function(a, b){ return Math.pow(a, b); },
        "~": function(a, b){ return Math.sqrt(a, b); }
    };
    o.s = { "^": 3, "~": 3, "*": 2, "/": 2, "%": 1, "+": 0, "-": 0 };
    o.u = {"+": 1, "-": -1}, o.p = {"(": 1, ")": -1};
};

MathProcessor.prototype.parse = function(e){
    for(var n, x, o = [], s = [x = this.RPN(e.replace(/ /g, "").split(""))]; s.length;)
        for((n = s[s.length-1], --s.length); n[2]; o[o.length] = n, s[s.length] = n[3], n = n[2]);
    for(; (n = o.pop()) != undefined; n[0] = this.o[n[0]](isNaN(n[2][0]) ? this.f(n[2][0]) : n[2][0], isNaN(n[3][0]) ? this.f(n[3][0]) : n[3][0]));
    return +x[0];
};

MathProcessor.prototype.methods = {
    "div": function(a, b){ return parseInt(a / b); },
    "frac": function(a){ return a - parseInt(a); },
    "sum": function(n1, n2, n3, n){ for(var r = 0, a, l = (a = arguments).length; l; r += a[--l]); return r; },
    "medium": function(a, b){ return (a + b) / 2; }
};

MathProcessor.prototype.error = function(s){
    throw new Error("MathProcessor: " + (s || "Erro na expressão"));
}

MathProcessor.prototype.RPN = function(e){
    var _, r, c = r = [, , , 0];
    if(e[0] in this.u || !e.unshift("+"))
        for(; e[1] in this.u; e[0] = this.u[e.shift()] * this.u[e[0]] + 1 ? "+" : "-");
    (c[3] = [this.u[e.shift()], c, , 0])[1][0] = "*", (r = [, , c, 0])[2][1] = r;
    (c[2] = this.v(e))[1] = c;
    (!e.length && (r = c)) || (e[0] in this.s && ((c = r)[0] = e.shift(), !e.length && this.error()));
     while(e.length){
        if(e[0] in this.u){
            for(; e[1] in this.u; e[0] = this.u[e.shift()] * this.u[e[0]] + 1 ? "+" : "-");
            (c = c[3] = ["*", c, , 0])[2] = [-1, c, , 0];
        }
        (c[3] = this.v(e))[1] = c;
        e[0] in this.s && (c = this.s[e[0]] > this.s[c[0]] ?
            ((c[3] = (_ = c[3], c[2]))[1][2] = [e.shift(), c, _, 0])[2][1] = c[2]
            : r == c ? (r = [e.shift(), , c, 0])[2][1] = r
            : ((r[2] = (_ = r[2], [e.shift(), r, ,0]))[2] = _)[1] = r[2]);
    }
    return r;
};

MathProcessor.prototype.v = function(e){
    if("0123456789.".indexOf(e[0]) + 1){
        for(var i = -1, l = e.length; ++i < l && "0123456789.".indexOf(e[i]) + 1;);
        return [+e.splice(0,i).join(""), , , 0];
    }
    else if(e[0] == "("){
        for(var i = 0, l = e.length, j = 1; ++i < l && (e[i] in this.p && (j += this.p[e[i]]), j););
        return this.RPN(l = e.splice(0,i), l.shift(), !j && e.shift());
    }
    else{
        var i = 0, c = e[0].toLowerCase();
        if((c >= "a" && c <= "z") || c == "_"){
            while(((c = e[++i].toLowerCase()) >= "a" && c <= "z") || c == "_" || (c >= 0 && c <= 9));
            if(c == "("){
                for(var l = e.length, j = 1; ++i < l && (e[i] in this.p && (j += this.p[e[i]]), j););
                return [e.splice(0,i+1).join(""), , , 0];
            }
        }
    }
    this.error();
}

MathProcessor.prototype.f = function(e){
    var i = 0, n;
    if(((e = e.split(""))[i] >= "a" && e[i] <= "z") || e[i] == "_"){
        while((e[++i] >= "a" && e[i] <= "z") || e[i] == "_" || (e[i] >= 0 && e[i] <= 9));
        if(e[i] == "("){
            !this.methods[n = e.splice(0, i).join("")] && this.error("Função \"" + n + "\" não encontrada"), e.shift();
            for(var a = [], i = -1, j = 1; e[++i] && (e[i] in this.p && (j += this.p[e[i]]), j);)
                j == 1 && e[i] == "," && (a.push(this.parse(e.splice(0, i).join(""))), e.shift(), i = -1);
            a.push(this.parse(e.splice(0,i).join(""))), !j && e.shift();
        }
        return this.methods[n].apply(this, a);
    }
};

BigNumber //JavaScript Class


Offers a extremely high precision level to make mathematical operations. For integers there is no limits and for floating point numbers, the class allows setting the maximum precision.

[UPDATED CODE AND HELP CAN BE FOUND HERE]

The class always returns new instances of BigNumber on the operations, so to the set value of a object, use the "set" method.


//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/bignumber [v1.0]

BigNumber = function(n, p, r){
    var o = this, i;
    if(n instanceof BigNumber){
        for(i in {precision: 0, roundType: 0, _sign: 0, _dec: 0}) o[i] = n[i];
        o._buffer = n._buffer.slice();
        return;
    }
    o.precision = isNaN(p = Math.abs(p)) ? BigNumber.defaultPrecision : p;
    o.roundType = isNaN(r = Math.abs(r)) ? BigNumber.defaultRoundType : r;
    o._sign = (n += "").charAt(0) == "-";
    o._dec = ((n = n.replace(/[^\d.]/g, "").split(".", 2))[0] = n[0].replace(/^0+/, "") || "0").length;
    for(i = (n = o._buffer = (n.join("") || "0").split("")).length; i; n[--i] = +n[i]);
    o.round();
};
with({$: BigNumber, o: BigNumber.prototype}){
    $.ROUND_HALF_EVEN = ($.ROUND_HALF_DOWN = ($.ROUND_HALF_UP = ($.ROUND_FLOOR = ($.ROUND_CEIL = ($.ROUND_DOWN = ($.ROUND_UP = 0) + 1) + 1) + 1) + 1) + 1) + 1;
    $.defaultPrecision = 40;
    $.defaultRoundType = $.ROUND_HALF_UP;
    o.add = function(n){
        if(this._sign != (n = new BigNumber(n))._sign) return n._sign = !n._sign, this.subtract(n);
        var o = new BigNumber(this), a = o._buffer, b = n._buffer, la = o._dec,
        lb = n._dec, n = Math.max(la, lb), i, r;
        la != lb && ((lb = la - lb) > 0 ? o._zeroes(b, lb, 1) : o._zeroes(a, -lb, 1));
        i = (la = a.length) == (lb = b.length) ? a.length : ((lb = la - lb) > 0 ? o._zeroes(b, lb) : o._zeroes(a, -lb)).length;
        for(r = 0; i; r = (a[--i] = a[i] + b[i] + r) / 10 >>> 0, a[i] %= 10);
        return r && ++n && a.unshift(r), o._dec = n, o.round();
    };
    o.subtract = function(n){
        if(this._sign != (n = new BigNumber(n))._sign) return n._sign = !n._sign, this.add(n);
        var o = new BigNumber(this), x = o.compare(n) + 1, a = x ? o : n, b = x ? n : o, la = a._dec, lb = b._dec, n = la, i, j;
        a = a._buffer, b = b._buffer, la != lb && ((lb = la - lb) > 0 ? o._zeroes(b, lb, 1) : o._zeroes(a, -lb, 1));
        for(i = (la = a.length) == (lb = b.length) ? a.length : ((lb = la - lb) > 0 ? o._zeroes(b, lb) : o._zeroes(a, -lb)).length; i;){
            if(a[--i] < b[i]){
                for(j = i; j && !a[--j]; a[j] = 9);
                --a[j], a[i] += 10;
            }
            b[i] = a[i] - b[i];
        }
        return o._sign = !x, o._dec = n, o._buffer = b, o.round();
    };
    o.multiply = function(n){
        var o = new BigNumber(this), r = o.compare(n = new BigNumber(n)) + 1, a = (r ? o : n)._buffer,
        b = (r ? n : o)._buffer, la = a.length, lb = b.length, x = new BigNumber, i, j, s;
        for(i = lb; i; x.set(x.add(new BigNumber(s.join("")))))
            for(s = (new Array(lb - --i)).join("0").split(""), r = 0, j = la; j;
            r += a[--j] * b[i], s.unshift(r % 10), r = r / 10 >>> 0);
        return r && x._buffer.unshift(r), o._dec = (o._buffer = x._buffer).length - la - lb + o._dec + n._dec, o.round();
    };
    o.divide = function(n){
        if((n = new BigNumber(n)) == "0") throw new Error("division by 0");
        var o = new BigNumber(this), a = o._buffer, b = n._buffer, la = a.length - o._dec,
        lb = b.length - n._dec, s = a._sign != b._sign, dec = 0, buffer = [], x = new BigNumber, y, i;
        la != lb && ((lb = la - lb) > 0 ? o._zeroes(b, lb) : o._zeroes(a, -lb));
        o._dec = a.length, n._dec = b.length;
        b = n, a._sign = false, b._sign = false;
        while(o != 0 && (buffer.length - dec) <= o.precision){
            x.set(0);
            for(i = 0; o.compare(y = x.add(b)) + 1 && ++i; x.set(y));
            if(!i){
                do ++i, o._buffer.push(0), ++o._dec;
                while(o.compare(b) < 0);
                !dec && (!buffer.length && buffer.push(0), dec = buffer.length);
                o._zeroes(buffer, --i);
                continue;
            }
            o.set(o.subtract(x)), buffer.push(i);
        }
        return o._buffer = buffer, o._dec = dec ? dec : buffer.length, o.round();
    };
    o.mod = function(n){
        return this.subtract(this.divide(n).intPart().multiply(n));
    };
    o.pow = function(n){
        var o = new BigNumber(this), i;
        if(n == 0) return o.set(1);
        for(i = Math.abs(n); --i; o.set(o.multiply(this)));
        return n < 0 ? o.set((new BigNumber(1)).divide(o)) : o;
    };
    o.set = function(n){
        return this.constructor(n), this;
    };
    o.compare = function(n){
        var a = this, la = this._dec, b = n, lb = n._dec, i, l;
        if(la != lb) return la > lb ? 1 : -1;
        for(la = (a = a._buffer).length, lb = (b = b._buffer).length, i = -1, l = Math.min(la, lb); ++i < l;)
            if(a[i] != b[i]) return a[i] > b[i] ? 1 : -1;
        return la != lb ? la > lb ? 1 : -1 : 0;
    }
    o.negate