Ir al contenido principal

Figuras, poligonos, herencia y polimorfismo en Javascript

Actualmente estoy ayudandole alguien muy especial con el aprendizaje de Javascript y OOP. Para tal objetivo le he asignado varios problemas que debe resolver con Herencia y ese pseudo poliformismo que tiene Javascript, pues nada me he inventado la primera parte de lo que seria la definicion de figuras con Javascript tales como un Cuadrado, Triangulo, Circulo, etc; por ahora el pintado solo muestra en la consola el area y algunos datos mas de la figura, pero la idea seria usar canvas en la segunda parte para imprimir las figuras y en el tercera parte algun mecanismo para obtener la informacion de las figuras del usuarios, pues nada aqui el codigo:


/**
 * User: jsanca
 * Date: 6/12/13
 * Time: 11:10 PM
 */

// Defines a point
function Point (x, y) {

    this.x = x;
    this.y = y;
} // Point


// Basic definition of a Figure, just a point in nowhere.
function Figure (point, name) {

    this.point = point;
    this.name = name;

    this.render = function () {

        console.log("figure: " + this.name + " " +this.point);
    }
} // Figure.

// the points defines some of the sides
function Square (point1, point2, name) {

    Figure.call(this, point1, name);
    this.point2 = point2;

    this.area = function () {

        var side =
            (this.point2.x == this.point.x)?
            this.point2.y - this.point.y:
            this.point2.x - this.point.x;

        return Math.pow(Math.abs(side), 2);
    }

    this.render = function () {

        console.log("square: " + this.name + ", area = " + this.area());
    }
} // Square.

Square.prototype.parent = Figure.prototype;
Square.prototype.constructor = Square;

// the points defines the point angles
function Triangle (point1, point2, point3, name) {

    Figure.call(this, point1, name);
    this.point2 = point2;
    this.point3 = point3;

    this.area = function () {

        var base = 0;
        var verticalHeight = 0;

        if (this.point2.x == this.point.x) {

            base = this.point2.y - this.point.y;
            verticalHeight = this.point.x - this.point3.x;
        } else {

            base = this.point2.x - this.point.x;
            verticalHeight = this.point.y - this.point3.y;
        }


        return 0.5 * Math.abs(base) * Math.abs(verticalHeight);
    }

    this.render = function () {

        console.log("triangle: " + this.name + ", area = " + this.area());
    }
} // Triangle.

Triangle.prototype.parent = Figure.prototype;
Triangle.prototype.constructor = Triangle;

// the points you pass are the diagonal of the rectangle.
function Rectangle (point1, point2, name) {

    Figure.call(this, point1, name);
    this.point2 = point2;

    this.area = function () {

        var width = this.point2.x - this.point.x;
        var height = this.point2.y - this.point.y;

        return Math.abs(width) * Math.abs(height);
    }

    this.render = function () {

        console.log("rectangle: " + this.name + ", area = " + this.area());
    }
} // Rectangle.

Rectangle.prototype.parent = Figure.prototype;
Rectangle.prototype.constructor = Rectangle;

// the points defines the radius
function Circle (point1, point2, name) {

    Figure.call(this, point1, name);
    this.point2 = point2;

    this.radius = function () {

        var radius =
            (this.point2.x == this.point.x)?
                this.point2.y - this.point.y:
                this.point2.x - this.point.x;

        return Math.abs(radius);
    }

    this.circumference = function () {

        var radius = this.radius();

        return 2 * Math.PI * radius;
    }

    this.area = function () {

        var radius = this.radius();

        return Math.PI * Math.pow(radius, 2);
    }

    this.render = function () {

        console.log("circle: " + this.name + ", area = " + this.area() + ", circumference = " + this.circumference() + ", radius = " + this.radius());
    }
} // Circle.

Circle.prototype.parent = Figure.prototype;
Circle.prototype.constructor = Circle;

console.log("Running");
var figuresArray = new Array(
    new Square  (new Point(10,10), new Point(10,30), "Cuadrado 1"),
    new Square  (new Point(10,10), new Point(15,10), "Cuadrado 2"),
    new Triangle(new Point(10,10), new Point(10,20), new Point(0,15), "Mi Triangulito"),
    new Rectangle(new Point(10,10), new Point(20,30), "Mi Rectangulo"),
    new Circle(new Point(10,10), new Point(10,25), "Mi Circulo")
);

figuresArray.forEach(
    function(entry) {

        console.log(entry);
        entry.render();
    }
);




Resultado

Running
Square { point=Point, name="Cuadrado 1", more...}
square: Cuadrado 1, area = 400
Square { point=Point, name="Cuadrado 2", more...}
square: Cuadrado 2, area = 25
Triangle { point=Point, name="Mi Triangulito", more...}
triangle: Mi Triangulito, area = 50
Rectangle { point=Point, name="Mi Rectangulo", more...}
rectangle: Mi Rectangulo, area = 200
Circle { point=Point, name="Mi Circulo", more...}
circle: Mi Circulo, area = 706.8583470577034, circumference = 94.24777960769379, radius = 15

Comentarios

Entradas más populares de este blog

Impensando acerca de las referencias en Java

Fue hace ya algún tiempo que pase un rato discutiendo con algunos compañeros acerca de si existe o no el paso por referencia; el discurso fue mucho hacia que en Java el comportamiento, en el supuestamente pasamos por referencia un objeto y por valor los objetos primitivos creo mucha polémica. Para ubicarnos en contexto veamos el siguiente ejemplo. public static void main(String[] args) { int value = 10; changeValue(value); System.out.println("value = " + value); User user = new User(); Name name = new Name(); user.setName(name); name.setName("jsanca"); name.setLastName("XXX"); user.setPassword("123queso"); System.out.println("user: " + user.getName().getName() + ", " + user.getName().getLastName() + ", " + user.getPassword()); changeValue1(user); System.out.println("user: " + user.getName().getName() + ", " + user.getName().getLastName() + ", " + user.ge...

Analizador de expresiones algebraicas recursivo decendente

Como les mencione en un post previo, estoy leyendo el libro el arte de programar en Java, el primer ejercicio consiste en un analizador de expresiones algebraicas recursivo descendente, el mismo consiste en la posibilidad de tomar una cadena que contenga una expresión matemática, la misma puede contener valores en punto flotante, sumar, restar, dividir, multiplicar, sacar exponente (potencia), uso de paréntesis para priorizar una operación, etc. A continuación clase a clase, con una pequeña explicación Lo primero que definiremos es una suite de excepciones para reportar errores, no tiene mucha ciencia, hay una para la division entre cero, cuando no existe una expresión valida, error de sintaxis o cuando los paréntesis no se encuentran balanceados, veamos package cap2; /** * Exception para reportar que hay al intentar dividir entre cero * * User: jsanca * Date: 4/16/13 * Time: 1:30 AM * @author jsanca */ public class DividedByZeroException extends RuntimeException { ...

Links acerca de usabilidad

Bueno esta haciendo un research acerca de usabilidad y decidi compartir algunos de los links mas interesantes: Este esta muy cool y dice por que son buenos, gmail #1: http://www.1stwebdesigner.com/design/well-designed-usable-sites/ Los mejores menus: http://www.kronikmedia.co.uk/blog/website-navigation-menu-design/3580/ Otro top ten: http://www.topsite.com/best/usability los CMS con mas usabilidad http://net.tutsplus.com/articles/web-roundups/top-10-most-usable-content-management-systems/ Las grandes companias que incorporan usabilidad en sus sistemas: http://www.siteiq.net/7806/the-2013-usability-top-10-ibm-leads-sap-soars-and-apple-screws-up-the-rankings-2 + Algo interesante: top ten de sitios de Universidades http://blog.thebrickfactory.com/2010/03/top-11-best-designed-university-websites/ Y estos son 10 videitos acerca de usabilidad: http://www.usefulusability.com/10-must-see-usability-videos/ Enjoy!