Skip to content

Instantly share code, notes, and snippets.

@QuadFlask
Last active May 1, 2016 03:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save QuadFlask/86f9b957f7e269a238f8b26411e0a9af to your computer and use it in GitHub Desktop.
Save QuadFlask/86f9b957f7e269a238f8b26411e0a9af to your computer and use it in GitHub Desktop.
[CodeWars] Algebraic List

리스트 구현

My Solution

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); };

겁나 간단하네??? 이미 자료구조가 재귀적인 형태라서 재귀를 잘 사용해야 하네...

Best Practice #1

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));
};

Best Practice #2

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));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment