把已经的接口适配成所需要的接口
现有 API,用于画点
let drawPoint = function(point){
process.stdout.write('.');
}
console.log = function (d){ process.stdout.write(d + ‘\n’); }; console.log() 是带换行的
现需要一个画矩形的类
class Point{
constructor(x, y){
this.x = x;
this.y = y;
}
toString(){
return `(${this.x}, ${this.y})`;
}
}
class Line{
constructor(start, end){
this.start = start;
this.end = end;
}
toString(){
return `${this.start.toString()} 到 ${this.end.toString()}`;
}
}
class VectorObject extends Array{
}
class VectorRectangle extends VectorObject{
constructor(x, y, width, height){
super();
this.push(new Line(new Point(x, y), new Point(x + width, y)));
this.push(new Line(new Point(x + width, y), new Point(x + width, y + height)));
this.push(new Line(new Point(x, y), new Point(x, y + height)));
this.push(new Line(new Point(x, y + height), new Point(x + width, y + height)));
}
}
let vectorObjects = [
new VectorRectangle(1, 1, 10, 10),
new VectorRectangle(5, 5, 20, 20)
]
构造把点转为直线的构造器,一直是一组点所构成
class LineToPointAdapter{
constructor(line){
this.hash = JSON.stringify(line).hashCode();
if(LineToPointAdapter.cache[this.hash]){
return
}
let points = [];
console.log(`${LineToPointAdapter.count++}: 正在为从 ${line.toString} 的直线生成点(没有使用缓存)`);
let left = Math.min(line.start.x, line.end.x);
let right = Math.max(line.start.y, line.end.y);
let top = Math.max(line.start.y, line.end.y);
let bottom = Math.min(line.start.y, line.end.y);
if(right - left === 0){
for(let y = bottom, y <= top; y++){
points.push(new Point(left, y));
}
} else if (top - bottom === 0){
for(let x = left, x <= right; x++){
points.push(new Point(x, top));
}
}
LineToPointAdapter.cache[this.hash] = points;
}
get items(){
return LineToPointAdapter.cache[this.hash];
}
}
LineToPointAdapter.count = 0;
LineToPointAdapter.cache = {};
let drawPoints = function(){
for(let vo of vectorObjects){
for(let line of vo){
let adapter = new LineToPointerAdapter(line);
adapter.items.forEach(drawPoint);
}
}
}
drawPoints();
drawPoints();
String.prototype.hashCode = function(){
if(Array.prototype.reduce){
return this.split("").reduce(function(a,b){
a=((a<<5)-a)+b.charCodeAt(0);
return a&a;
}, 0)
}
let hash = 0;
if(this.length ===0) return hash;
for(let i=0;i<this.length;i++){
count character = this.charCodeAt(i);
hash = ((hash<<5)-hash)+character;
hash = hash & hash;
}
return hash;
}