Tag Archives: Enumerable

Prototype Javascript Framework – Enumerable

지금까지 제 생각에 중요하다 생각되는것부터 하나하나 공부를 하고 있습니다. 이번에 과연 우선순위가 있다면 무엇일까를 생각하다가 Function등과 고민끝에 Enumerable이 선택 되었습니다^^a

Enumerable이라는 말 자체가 ‘열거, 혹은 셈이 가능한’ 이라는 뜻입니다. 열거가 가능한 클래스라는 뜻이죠.

실제로 자바스크립트 Native 메서드인 each를 재정의하고 있으며, 많은 다른 Prototype 클래스들이 열거가능한 기능을 갖기 위해 Enumerable 클래스를 상속받고 있습니다.

소스를 뒤져보니 다음의 녀석들이 Enumerable을 상속받고 있군요.
Array, Hash, ObjectRange, Ajax.Responders, Element.ClassNames

Context 파라미터 —————————————————————————————————
모든 Enumerable을 가지고 있는 클래스들은 순환문 실행시 옵션 파라미터로 컨텍스트 오브젝트를 입력할 수 있습니다.
이 오브젝트는 순환문 내부에 Bind되며 this로 접근할 수 있게 됩니다.

예제)
[code]var myObject = {};


[‘foo’, ‘bar’, ‘baz’].each(function(name, index) {
  this[name] = index;
}, myObject);

// myObject라는 Context 객체를 사용하였음
//-> { foo: 0, bar: 1, baz: 2}[/code]

Aliases : 메서드 별칭 ———————————————————————————————–
Enumerable의 메서드들은 다른 이름을 가졌지만 같은 기능을 하는 메서드들이 많이 있습니다. 루비등과 같은 언어에 적응한 개발자들의 편의를 생각한 것 같습니다.



  • map메서드는 collect메서드와 동일합니다.

  • find메서드는 detect메서드와 동일합니다.

  • findAll메서드는 select메서드와 동일합니다.

  • include메서드는 member메서드와 동일합니다.

  • entries메서드는 toArray메서드와 동일합니다.

실제로 소스에도 저 메서드들의 실제는 없고 참조만 되어있습니다.
[code]Object.extend(Enumerable, {
  map:     Enumerable.collect,
  find:    Enumerable.detect,
  select:  Enumerable.findAll,
  filter:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray,
  every:   Enumerable.all,
  some:    Enumerable.any
});[/code]

collect, invoke, pluck 그리고 each ——————————————————————————-
초보자들은 모든 열거 객체들에 대해 each를 이용하여 해결할려고 할것입니다. 하지만 필요에 따라 collect같은것을 사용하면 더욱 간단하고 멋지게 문제를 해결할 수있게 됩니다. 또한 더 나은 퍼포먼스를 기대할수도 있습니다.



  • 모든 엘리먼트들에 대해 같은 메서드를 수행해야 할때는 invoke를 사용하십시오.

  • 모든 엘리먼트들의 같은 프로퍼티를 가져와야 할 경우에는 pluck을 사용하십시오.


reject와 findAll VS partition
—————————————————————————————
findAll/select 메서드는 조건문을 두어 조건에 찾을 갖는 값들만을 모아 배열로 반환합니다. 반대로 reject 메서드는 조건에 거짓이 되는 값들만을 모아 배열로 반환합니다. 하지만 만약에 조건의 참과 거짓 둘다 필요하다면 이 메서드들을 각각 한번씩 두번 수행해야 할까요? 실제로 Prototype에서는 partition이라는 둘다를 반환해 주는 훌륭한 메서드를 가지고 있습니다.


자신이 만든 객체에 Enumerable 믹싱하기
————————————————————————–
이번에는 자신이 만든객체가 열거가능한 기능을 가졌으면 할때, 다이나믹하게 내부의 값들을 취합하거나 다른 작업을 하고 싶을때 Enumerable 클래스를 상속하면 됩니다. Enumerable은 기본적으로 순환문의 작업을 할때 _each라는 이름의 메서드를 호출합니다. Enumerable 클래스를 상속한 후에 _each메서드를 오버라이딩 하면 내가 만든 객체를 내가 원하는대로 작동하도록 수정할 수 있습니다.

예제)
[code]var YourObject = Class.create();
Object.extend(YourObject.prototype, Enumerable);
Object.extend(YourObject.prototype, {
  initialize: function() {
    // 생성자 처리를 위한 코드
  },
  _each: function(iterator) {
    // 반복문 코드
  },
  // 다른 메서드는 여기, Enumerable클래스의 메서드와 동일할경우 오버라이딩 됨
});


var obj = new YourObject();
// 다음과 같은 Enumerable 메서드를 사용 가능하게 됨
obj.pluck(‘somePropName’);
obj.invoke(‘someMethodName’);
obj.size();
// 기타[/code]

Enumerable Methods ———————————————————————————————-
all : 순환값이 모두 참이면 참을 반환하면 하나라도 거짓이면 거짓을 반환합니다.
[code]all([iterator = Prototype.K[, context]]) -> Boolean[/code]

예제)
[code][].all()
// -> true (거짓을 반환하는 값이 한개도 없었음)
$R(1, 5).all()
// -> true (1부터 5까지의 숫자는 모두 참)
[0, 1, 2].all()
// -> false (0은 거짓임)
[9, 10, 15].all(function(n) { return n >= 10; })
// -> false (조건문을 사용하였음. 10보다 큰 15가 존재하므로 거짓)
$H({ name: ‘John’, age: 29, oops: false }).all(function(pair) { return pair.value; })
// -> false (oops의 값이 false이므로 거짓)[/code]

any : all과 상반되는 기능을 하며 하나라도 참이면 참을 반환합니다.
[code]any([iterator = Prototype.K[, context]]) -> Boolean[/code]

예제)
[code][].any()
// -> false (하나이상의 참인 값이 존재하지 않음)
$R(0, 2).any()
// -> true (두번째 순환값인 1에서 메서드 종료와 함께 참을 반환)
[2, 4, 6, 8, 10].any(function(n) { return 0 == n % 3; })
// -> true (순환 3번째 값 6에서 참을 반환)
$H({ opt1: null, opt2: false, opt3: ”, opt4: ‘pfew!’ }).any(function(pair) { return pair.value; })
// -> true (opt4의 값이 있으므로 참 반환)[/code]

collect/map : 순환문의 결과값을 묶어 배열로 반환합니다.
[code]collect(iterator[, context]) -> Array[/code]

예제)
[code][‘Hitch’, “Hiker’s”, ‘Guide’, ‘To’, ‘The’, ‘Galaxy’].collect(function(s) {
  return s.charAt(0).toUpperCase();
}).join(”)
// -> ‘HHGTTG’


$R(1,5).collect(function(n) {
  return n * n;
})
// -> [1, 4, 9, 16, 25][/code]

detect/find : 순환문에 조건을 두어 조건을 만족하는 첫번째 값을 반환합니다.
[code]find(iterator) -> firstElement | undefined[/code]

예제)
[code]function isPrime(n) {
  if (2 > n) return false;
  if (0 == n % 2) return (2 == n);
  for (var index = 3; n / index > index; index += 2)
    if (0 == n % index) return false;
  return true;
}


$R(10,15).find(isPrime)
// -> 11


[ ‘hello’, ‘world’, ‘this’, ‘is’, ‘nice’].find(function(s) {
  return s.length <= 3;
})
// -> ‘is'[/code]

each : Enumerable에서 가장 기본적인 스타일을 갖는 순환문 처리 메서드입니다.
[code]each(iterator[, context]) -> Enumerable[/code]
each메서드는 Enumerable에서 가장 핵심이 되는 메서드입니다. 순환문 함수는 두 파라미터를 가질 수 있습니다.



  1. 순환문이 접하는 현재 엘리먼트

  2. 숫자 인덱스, 0에서 시작하며 순환이 돌때마다 1씩 중가

기타 옵션으로 context 파라미터를 사용할 수 있는데 위에서 설명하였듯이 this 키워드가 여기서 지정된 context 객체가 됩니다.

$break와 $continue
순환문에서 $break와 $continue를 사용하여 순환문을 빠져나오거나 다음 순환으로 점프를 뛸 수 있습니다.
하지만 이제 $continue는 deprecated 되었군요. 간단하게 return을 사용하면 $continue와 동일한 동작을 한다고 합니다.

예제)
[code][‘one’, ‘two’, ‘three’].each(function(s) {
  alert(s);
});
// alerts -> ‘one’, ‘two’, ‘three’


[ ‘hello’, ‘world’].each(function(s, index) {
  alert(index + ‘: ‘ + s);
});
// alerts -> ‘0: hello’ then ‘1: world’


var result = [];
$R(1,10).each(function(n) {
  if (0 == n % 2)
    throw $continue;
  if (n > 6)
    throw $break;
  result.push(n);
});
// result -> [1, 3, 5][/code]

each VS _each
Enumerable 클래스의 순환은 기본적으로 _each메서드를 호출합니다. 하지만 _each는 하나의 인자밖에 받을 수 없습니다. 기본적으로 Enumerable.each 메서드는 _each메서드의 래핑 메서드입니다. 하지만 다음과 같은 이점을 얻을 수 있습니다.



  1. break/continue를 지원함

  2. 값과 인덱스를 인자로 받을 수 있음

최적화 버전
each는 기본적이면서도 매우 다양하게 사용될 수 있는 메서드입니다. 하지만 Enumerable클래스에는 invoke와 같이 매우 특화된 간편하면서도 강력한 메서드들이 많이 마련되어있습니다. 잘 알아두었다가 필요에 따라 적절히 사용하는것이 중요할 것 같습니다.

eachSlice : 원하는 사이즈만큼의 그룹단위로 쪼개어 반환합니다.
[code]eachSlice(size[, iterator = Prototype.K[, context]]) -> [slice…][/code]

예제)
[code]var students = [
  { name: ‘Sunny’, age: 20 }, { name: ‘Audrey’, age: 21 },
  { name: ‘Matt’, age: 20 }, { name: ‘Elodie’, age: 26 },
  { name: ‘Will’, age: 21 }, { name: ‘David’, age: 23 },
  { name: ‘Julien’, age: 22 }, { name: ‘Thomas’, age: 21 },
  { name: ‘Serpil’, age: 22 }
];


students.eachSlice(4, function(toon) {
  return toon.pluck(‘name’);
})


// -> [ [‘Sunny’, ‘Audrey’, ‘Matt’, ‘Elodie’],
// [‘Will’, ‘David’, ‘Julien’, ‘Thomas’],
// [‘Serpil’] ]


students.eachSlice(2).first()
// -> [{ name: ‘Sunny’, age: 20 }, { name: ‘Audrey’, age: 21 }][/code]

entries/toArray : 모든종류의 열거형 객체를 Array로 변경하여 반환합니다.
[code]toArray() -> Array[/code]

예제)
[code]$R(1, 5).toArray()
// -> [1, 2, 3, 4, 5][/code]

findAll/select : 조건에 맞는 모든 값을 반환합니다.
[code]findAll(iterator[, context]) -> Array[/code]

예제)
[code]$R(1, 10).findAll(function(n) { return 0 == n % 2; })
// -> [2, 4, 6, 8, 10]


[ ‘hello’, ‘world’, ‘this’, ‘is’, ‘nice’].findAll(function(s) {
  return s.length >= 5;
})
// -> [‘hello’, ‘world’] [/code]

grep : match필터를 사용하여 매칭이 되는 값만을 반환합니다. 선택된 값들에 대해 반복문 함수를 지정할 수 있습니다.
[code]grep(regex[, iterator = Prototype.K[, context]]) -> Array[/code]

예제)
[code]// 반복되는 문자열을 가지고 있는 값을 반환
[‘hello’, ‘world’, ‘this’, ‘is’, ‘cool’].grep(/(.)\1/)
// -> [‘hello’, ‘cool’]


// 0이나 5로 끝나는 숫자 모두를 반환
$R(1,30).grep(/[05]$/)
// -> [5, 10, 15, 20, 25, 30]


// 위의 결과에서 -1을 할경우
$R(1,30).grep(/[05]$/, function(n) { return n – 1; })
// -> [4, 9, 14, 19, 24, 29]


// 엘리먼트중에 CSS 셀렉터를 사용하여 선택함
$(‘foo’).childElements().grep(new Selector(“li.active”));[/code]

inGroupOf : 고정된 크기로 그룹단위로 값을 묶어 반환합니다.
[code]inGroupsOf(size[, filler = null]) -> [group…][/code]
이 메서드는 eachSlice와 동일합니다. 하지만 반환되어나오는 그룹의 사이즈가 항상 동일합니다. 값이 없을 경우 null이 채워집니다.

예제)
[code]var students = [
  { name: ‘Sunny’, age: 20 }, { name: ‘Audrey’, age: 21 },
  { name: ‘Matt’, age: 20 }, { name: ‘Elodie’, age: 26 },
  { name: ‘Will’, age: 21 }, { name: ‘David’, age: 23 },
  { name: ‘Julien’, age: 22 }, { name: ‘Thomas’, age: 21 },
  { name: ‘Serpil’, age: 22 }
];


students.pluck(‘name’).inGroupsOf(4)
// -> [ [‘Sunny’, ‘Audrey’, ‘Matt’, ‘Elodie’],
// [‘Will’, ‘David’, ‘Julien’, ‘Thomas’],
// [‘Serpil’, null, null, null] ][/code]

include/member : 열거객체안의 원하는 값이 있는지 확인합니다.
[code]include(object) -> Boolean[/code]

예제)
[code]$R(1,15).include(10)
// -> true


[‘hello’, ‘world’].include(‘HELLO’)
// -> false


[1, 2, ‘3’, ‘4’, ‘5’].include(3)
// -> true (==를 사용하여 비교함. 타입이 무시됨)[/code]

inject : 베이스가 되는 값을 두고 반복문을 돌아 최종 적으로 베이스값을 반환합니다.
[code]inject(accumulator, iterator[, context]) -> accumulatedValue[/code]

예제)
[code]$R(1,10).inject(0, function(acc, n) { return acc + n; })
// -> 55 (sum of 1 to 10)

$R(2,5).inject(1, function(acc, n) { return acc * n; })
// -> 120 (factorial 5)

[‘hello’, ‘world’, ‘this’, ‘is’, ‘nice’].inject([], function(array, value, index) {
  if (0 == index % 2)
    array.push(value);
  return array;
})
// -> [‘hello’, ‘this’, ‘nice’]

// 참조를 어떻게 사용하는가?
var array1 = [];
var array2 = [1, 2, 3].inject(array1, function(array, value) {
  array.push(value * value);
  return array;
});
array2
// -> [1, 4, 9]
array1
// -> [1, 4, 9]
array2.push(16);
array1
// -> [1, 4, 9, 16][/code]

invoke : 모든 열거형 값에 같은 메서드를 수행합니다. each와 collect를 이용한 최적화된 메서드입니다.
[code]invoke(methodName[, arg…]) -> Array[/code]

예제)
[code][‘hello’, ‘world’, ‘cool!’].invoke(‘toUpperCase’)
// [‘HELLO’, ‘WORLD’, ‘COOL!’]


[‘hello’, ‘world’, ‘cool!’].invoke(‘substring’, 0, 3)
// [‘hel’, ‘wor’, ‘coo’]


// 당연히 Prototype의 확장이 이루어진 엘리먼트는 다음과 같은것도 가능함
$(‘navBar’, ‘adsBar’, ‘footer’).invoke(‘hide’)


// 다음과 같이 invoke를 연달아 사용하는것도 가능함
$$(‘#windows div.close’).invoke(‘addClassName’, ‘active’).invoke(‘show’);[/code]

max : 입력된 열거형 값들중에 가장 큰 값이 반환됩니다. 값이 같을 경우 가장 마지막 값이 반환됩니다.
[code]max([iterator = Prototype.K[, context]]) -> maxValue[/code]

예제)
[code]$R(1,10).max()
// -> 10


[‘hello’, ‘world’, ‘gizmo’].max()
// -> ‘world’


function Person(name, age) {
  this.name = name;
  this.age = age;
}


var john = new Person(‘John’, 20);
var mark = new Person(‘Mark’, 35);
var daisy = new Person(‘Daisy’, 22);


[john, mark, daisy].max(function(person) {
  return person.age;
})
// -> 35[/code]

min : 입력된 열거형 값들중에 가장 작은 값이 반환됩니다. 같이 같을 경우 가장 첫번째 값이 반환됩니다.
[code]min([iterator = Prototype.K[, context]]) -> minValue[/code]

예제)
[code]$R(1,10).min()
// -> 1


[‘hello’, ‘world’, ‘gizmo’].min()
// -> ‘gizmo’


function Person(name, age) {
  this.name = name;
  this.age = age;
}


var john = new Person(‘John’, 20);
var mark = new Person(‘Mark’, 35);
var daisy = new Person(‘Daisy’, 22);


[john, mark, daisy].min(function(person) {
  return person.age;
})
// -> 20[/code]

partition : 조건문을 두어 참을 갖는 객체 그룹과 거짓을 갖는 객체 그룹 두가지 그룹으로 결과가 반환됩니다.
[code]partition([iterator = Prototype.K[, context]]) -> [TrueArray, FalseArray][/code]
이 메서드는 findAll/select와 reject메서드가 하는 두가지 일을 동시에 하는 메서드입니다.

예제)
[code][‘hello’, null, 42, false, true, , 17].partition()
// -> [[‘hello’, 42, true, 17], [null, false, undefined]]


$R(1, 10).partition(function(n) {
  return 0 == n % 2;
})
// -> [[2, 4, 6, 8, 10], [1, 3, 5, 7, 9]][/code]

pluck : collect메서드를 최적하한 메서드입니다. 모든 객체의 프로퍼티 값을 가져옵니다.
[code]pluck(propertyName) -> Array[/code]

예제)
[code][‘hello’, ‘world’, ‘this’, ‘is’, ‘nice’].pluck(‘length’)
// -> [5, 5, 4, 3, 4]


document.getElementsByClassName(‘superfluous’).pluck(‘tagName’).sort().uniq()
// -> superfluous라는 클래스명을 가진 엘리먼트들의 태그명을 중복을 제거하여 정렬[/code]

reject : 조건문에 거짓이 되는 값들을 반환합니다.
[code]reject(iterator[, context]) -> Array[/code]

예제)
[code]$R(1, 10).reject(function(n) { return 0 == n % 2; })
// -> [1, 3, 5, 7, 9]


[ ‘hello’, ‘world’, ‘this’, ‘is’, ‘nice’].reject(function(s) {
  return s.length >= 5;
})
// -> [‘this’, ‘is’, ‘nice’][/code]

size : 열거형 객체의 길이를 반환합니다.
[code]size() -> Number[/code]

예제)
[code]$R(1, 10).size()
// -> 10


[‘hello’, 42, true].size()
// -> 3


$H().size()
// -> 0[/code]

sortBy : 특정한 조건에 맞춰 정렬합니다.
[code]sortBy(iterator[, context]) -> Array[/code]

예제)
[code][‘hello’, ‘world’, ‘this’, ‘is’, ‘nice’].sortBy(function(s) { return s.length; })
// -> ‘is’, ‘this’, ‘nice’, ‘hello’, ‘world’]


[‘hello’, ‘world’, ‘this’, ‘is’, ‘cool’].sortBy(function(s) {
  var md = s.match(/[aeiouy]/g);
  return null == md ? 0 : md.length;
})
// -> [ ‘world’, ‘this’, ‘is’, ‘hello’, ‘cool’] (모음순 순서) [/code]

zip : 두개 이상의 열거형 객체를 합칠때 사용합니다. 배열형태로 혼합되어 반환되나 형태를 마음대로 정할 수 있습니다.
[code]zip(Sequence…[, iterator = Prototype.K]) -> Array[/code]

예제)
[code]var firstNames = [‘Justin’, ‘Mislav’, ‘Tobie’, ‘Christophe’];
var lastNames = [‘Palmer’, ‘Marohni?’, ‘Langel’, ‘Porteneuve’];


firstNames.zip(lastNames)
// -> [[‘Justin’, ‘Palmer’], [‘Mislav’, ‘Marohni?’], [‘Tobie’, ‘Langel’], [‘Christophe’, ‘Porteneuve’]]


firstNames.zip(lastNames, function(a) { return a.join(‘ ‘); })
// -> [‘Justin Palmer’, ‘Mislav Marohni?’, ‘Tobie Langel’, ‘Christophe Porteneuve’]


var cities = [‘Memphis’, ‘Zagreb’, ‘Montreal’, ‘Paris’];
firstNames.zip(lastNames, cities, function(p) {
  return p[0] + ‘ ‘ + p[1] + ‘, ‘ + p[2];
})
// -> [‘Justin Palmer, Memphis’, ‘Mislav Marohni?, Zagreb’, ‘Tobie Langel, Montreal’, ‘Christophe Porteneuve, Paris’]


firstNames.zip($R(1, 100), function(a) { return a.reverse().join(‘. ‘); })
// -> [‘1. Justin’, ‘2. Mislav’, ‘3. Tobie’, ‘4. Christophe’][/code]