Skip to content

Instantly share code, notes, and snippets.

@avipinto
Forked from padolsey/c.md
Created July 18, 2012 19:24
Show Gist options
  • Save avipinto/3138260 to your computer and use it in GitHub Desktop.
Save avipinto/3138260 to your computer and use it in GitHub Desktop.
JS challenge

Implement Point so that:

new Point( new Point(10, 20) + new Point(30, 50) ).toString() === '{40,70}'

Must be generic and be able to handle x and y values from 0..999 (integers only)

Minor hint: you'll need to implement valueOf and toString methods.

My Code:

function Point(x,y){

 if(typeof(x) == "string")
 {
   this.x = this.y = 0;
   var composed = x.split(",");
   for(var i=0,len=composed.length; i<len; i+=2)
   {
     this.x +=(parseInt(composed[i]) || 0);
     this.y +=(parseInt(composed[i+1]) || 0);
   } 
 }
 else{this.x=x;this.y=y;}
}
Point.prototype.valueOf = function(){return this.x + "," + this.y + ","};
Point.prototype.toString = function(){return "{" + this.x + "," + this.y + "}"};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment