리스트 구현
function Cons(head, tail) {
this.head = head;
this.tail = tail;
}
Cons.fromArray = function(array) {
var tail = null;
while(array.length>0) {
tail = new Cons(array.pop(), tail);
}
return tail;
};
function filter(list, predicate) {
var cons = list;
var a = [];
while(cons) {
if (predicate(cons.head)) a.push(cons.head);
cons = cons.tail;
}
return Cons.fromArray(a);
}
function map(list, mapper) {
var cons = list;
var a = [];
while(cons) {
a.push(mapper(cons.head));
cons = cons.tail;
}
return Cons.fromArray(a);
}
Cons.prototype.filter = function(predicate){ return filter(this,predicate); };
Cons.prototype.map = function(mapper){ return map(this, mapper); };
겁나 간단하네??? 이미 자료구조가 재귀적인 형태라서 재귀를 잘 사용해야 하네...
Cons.fromArray = function(array) {
return array.reduceRight(function(list, e) { return new Cons(e, list); }, null);
};
Cons.prototype.filter = function(predicate) {
var tail = this.tail && this.tail.filter(predicate);
return predicate(this.head) ? new Cons(this.head, tail) : tail;
};
Cons.prototype.map = function(mapper) {
return new Cons(mapper(this.head), this.tail && this.tail.map(mapper));
};
Cons.fromArray = ([head, ...tail]) =>
new Cons(head, tail.length ? Cons.fromArray(tail) : null);
Cons.prototype.filter = function(predicate) {
const tail = this.tail && this.tail.filter(predicate);
return predicate(this.head) ? new Cons(this.head, tail) : tail;
};
Cons.prototype.map = function(mapper) {
return new Cons(mapper(this.head), this.tail && this.tail.map(mapper));
}