Skip to content

Instantly share code, notes, and snippets.

@alejandro
Created September 29, 2012 06:15
Show Gist options
  • Select an option

  • Save alejandro/3803344 to your computer and use it in GitHub Desktop.

Select an option

Save alejandro/3803344 to your computer and use it in GitHub Desktop.
Punto en ES6
module.exports = Punto
var util = require('util')
function Punto(coordenadas) {
if (!(this instanceof Punto)) return new Punto(coordenadas)
util._extend(this, coordenadas)
}
Punto.fn = Punto.prototype
Punto.fn.__defineGetter__('distancia', function(){
return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2))
})
Punto.fn.__defineGetter__('area', function(){
return (0.5 * Number(this.x) * Number(this.y))
})
Punto.fn.extend = function(coordenada, mas) {
if (!this[coordenada]) throw new TypeError('Coordenada Inválida')
this[coordenada] += mas
return this
}
var util = require('util')
var EventEmitter = require('events').EventEmitter
class Punto extends EventEmitter {
constructor (coordenadas){
util._extend(this, coordenadas)
}
extend (coordenada, mas){
if (!this[coordenada]) throw new TypeError('Coordenada Inválida')
this[coordenada] += mas
this.emit('change', `Hooray! ${coordenada} ha cambiado`)
return this
}
get distancia(){
return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2))
}
get area(){
return (0.5 * Number(this.x) * Number(this.y))
}
}
// TEST:
var punto = new Punto({x:1, y:2})
punto.on('change', function (msg){
console.log(msg)
})
// comprobando sus propiedades
assert.equal(punto.x, 1)
assert.equal(punto.distancia, 2.23606797749979)
assert.equal(punto.area, 1)
punto.extend('x', 3) // => 'Hooray! x ha cambiado'
assert.equal(punto.distancia, 4.47213595499958)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment