Category Archives: JAVASCRIPT

Prototype Javascript Framework – Function

이번에는 Prototype을 사용하며 꼭! 알아야 하지만 많은 분들이 모르시고 필요성을 모르시는 분들께 정말 중요한 자료가 될것 같네요.

Prototype에서는 Function이라는 클래스가 있습니다. 정말 몰라도 될것 같은 이름이죠. 기껏해야 function으로 함수 만드는 방법을 조금 확장한게 아닐까 싶은 클래스입니다.

하지만! 이것을 알면 여러분의 개발이 확실히 편해지는 멋진 녀석입니다. 한번 알아보도록 하죠.

바인딩이란 무엇인가? ———————————————————————————————–
Prototype에서 function과 관련하여 가장 중점을 두는 부분은 Binding입니다. 바인딩은 기본적으로 함수(메서드)가 실행될 때 this 키워드가 그 함수 자체가 되거나 혹은 다른 객체가 되는것을 말합니다. 당신은 bind()라는 메서드만 알면 여기에 관련된 모든 문제가 해결됩니다.

Prototype은 두가지 개발상의 문제를 해결하였습니다. 하나는 모든 함수(메서드)에 대하여 바인딩을 할수 있도록 하였다는것과 다른 한가지는 이벤트 핸들러에서 호출되는 함수(메서드)에 특화된 바인딩을 구현하였다는 점입니다.

Function Methods ————————————————————————————————-

argumentNames : 메서드나 함수에서 인자(파라미터)를 정의한 경우 해당 인자의 이름을 반환합니다.
[code]someFunction.argumentNames() -> Array[/code]

예제)
[code]var fn = function(foo, bar) {
  return foo + bar;
};


fn.argumentNames();
//-> [‘foo’, ‘bar’]


Prototype.emptyFunction.argumentNames();
//-> [][/code]

bind : 다른 객체로 함수(메서드)를 포장하여 실행 스코프를 고정합니다.
[code]bind(thisObj[, arg…]) -> Function[/code]
보통 bind를 말하기를 this를 바꾼다라고 표현하기도 합니다만, 정확하게는 실행되는 위치, 즉 Scope를 고정한다고 말하는 것이 맞습니다.

문제가 있는 예제)
[code]window.name = “the window object”


function scopeTest() {
  return this.name
}


// 글로벌 Scope로 함수 호출
scopeTest()
// -> “the window object”


var foo = {
  name: “the foo object!”,
  otherScopeTest: function() { return this.name }
}


foo.otherScopeTest()
// -> “the foo object!”[/code]
[code]// test함수가 foo.otherScopeTest() 메서드를 참조
window.test = foo.otherScopeTest


// 함수 호출, Scope는 글로벌(window)
test()
// -> “the window object”[/code]

예제)
[code]var obj = {
  name: ‘A nice demo’,
  fx: function() {
    alert(this.name);
  }
};


window.name = ‘I am such a beautiful window!’;


function runFx(f) {
  f();
}


var fx2 = obj.fx.bind(obj);
runFx(obj.fx);
// -> alerts ‘I am such a beautiful window!’
runFx(fx2);
// -> alerts ‘A nice demo'[/code]
또한, 다음과 같이 필요한 인자를 얼마든지 추가할 수 있습니다. arguments로 받아서 사용할 수 있습니다.
[code]var obj = {
  name: ‘A nice demo’,
  fx: function() {
    alert(this.name + ‘\n’ + $A(arguments).join(‘, ‘));
  }
};


var fx2 = obj.fx.bind(obj, 1, 2, 3);
fx2(4, 5);
// 객체의 name과 “1, 2, 3, 4, 5″가 출력[/code]
여기서 알 수 있듯이 바인딩 후 인자는 계속 추가되는 식으로 사용되는것을 알 수 있습니다.

아직도 바인딩이 이해가 잘 안되신다면 다음의 포스팅을 봐보세요. 정말 잘 만들어져있습니다. [ 글보기 ]

bindAsEventListener : 이벤트 리스너에 특화된 바인딩 메서드입니다.
[code]bindAsEventListener(thisObj[, arg…]) -> Function[/code]
이 메서드를 이해하기 전에 바인딩에 대해 제대로 이해하지 못하고 있다면 우선 bind()메서드부터 이해하도록 하세요. 이 메서드는 이벤트 핸들러에 맞춰 만들어진 메서드입니다. this 오브젝트를 변경할 수 있으며 Event.observe등에 맞추어 사용될 수 있습니다.

예제)
[code]var obj = { name: ‘A nice demo’ };


function handler(e) {
  var tag = Event.element(e).tagName.toLowerCase();
  var data = $A(arguments);
  data.shift();
  alert(this.name + ‘\nClick on a ‘ + tag + ‘\nOther args: ‘ + data.join(‘, ‘));
}


Event.observe(document.body, ‘click’, handler.bindAsEventListener(obj, 1, 2, 3));
// obj 객체의 name이 출력되고 태그명이 소문자로 변경되어 출력
// 또한 추가로 입력된 인자인 ‘1, 2, 3’이 출력[/code]

curry : bind()와 마찬가지로 scope를 유지하는 메서드입니다. 한개 이상의 인자를 미리 입력해 둘 수 있습니다.
[code]curry(arg…) -> Function[/code]

예제)
[code]String.prototype.splitOnSpaces = String.prototype.split.curry(” “);
“foo bar baz thud”.splitOnSpaces();
//-> [“foo”, “bar”, “baz”, “thud”][/code]

defer : JS를 해석하는 인터프리터가 쉴때 함수(메서드)를 실행합니다.
[code]defer(arg…) -> Number[/code]
반환되는 ID값을 가지고 window.clearTimeout으로 중단 시킬 수 있습니다.

예제)
[code]function hideNewElement() {
  $(‘inserted’).hide();
};


function insertThenHide(markup) {
  $(‘container’).insert(markup);


  // 위의 명령이 완료되어 DOM 트리가 완성되었을때 다음이 실행되어야 함
  hideNewElement.defer();
}


insertThenHide(“<div id=’inserted’>Lorem ipsum</div>”);[/code]
이 메서드는 인터프리터의 Call Stack이 쉴때 메서드를 수행하게끔 하는 명령입니다. 위와 같은 경우에는 DOM 트리에 추가가 끝나지 않은 상황에서 hide()를 하게 되면 에러가 생기겠지요. 그것을 방지할 수 있습니다.

delay : 함수(메서드)를 실행시에 실행 시간을 지연 시킬 수 있습니다.
[code]delay(seconds[, arg…]) -> Number[/code]
이 메서드는 window.setTimeout과 동일한 역할을 합니다. 인터프리터가 쉬는 시간에 실행시키기 위해서라면 defer()를 사용하시기 바랍니다. defer와 마찬가지로 반환되는 ID값을 가지고 window.clearTimeout으로 중단 시킬 수 있습니다.

예제)
[code]// 이전 :
window.setTimeout(function() {
  Element.addClassName(‘foo’, ‘bar’);
}, 1000);


// 이후 :
Element.addClassName.delay(1, ‘foo’, ‘bar’);


// 타임아웃 제거, 아래는 수행되지 않음
var id = Element.hide.delay(5, ‘foo’);
window.clearTimeout(id);[/code]

methodize : 이 메서드는 어떤 함수던지 메서드 형식으로 만들어 버립니다. 첫번째 인자는 this가 됩니다.
[code]someFunction.methodize() -> Function[/code]

예제)
[code]// 간단한 target 객체에 foo값을 담는 함수
var fn = function(target, foo) {
  target.value = foo;
};


var object = {};


// 기존의 함수 사용
function fn(object, ‘bar’);
object.value
//-> ‘bar’


// object에 methodize를 이용해 새로운 메서드를 생성함
// 첫번째 인자는 this가 되므로 인자의 수가 한개 줄음
object.fnMethodized = fn.methodize();
object.fnMethodized(‘boom!’);
object.value
//-> ‘boom!'[/code]

wrap : 기존의 함수에 새로운 함수를 래핑합니다.
[code]wrap(wrapperFunction[, arg…]) -> Function[/code]
자바의 스프링 프레임워크를 사용하고 있는 저를 흥분되게 하는 메서드였습니다. 조금 우스운 수준이긴 하지만 자바스크립트에서 관점지향프로그래밍(AOP)를 지원하게 하는군요. 특정 메서드가 수행되기 전에 내가 원하는 다른 일을 처리 할 수 있습니다. 잘 쓰면 정말 동적인 멋진 어플리케이션을 만들 수 있을 것 같습니다.

예제)
[code]String.prototype.capitalize = String.prototype.capitalize.wrap(
  function(proceed, eachWord) {
    if (eachWord && this.include(” “)) {
      // 하나하나의 단어들에 대해 capitalize를 수행함
      return this.split(” “).invoke(“capitalize”).join(” “);
    } else {
      // 기존의 메서드 수행
   return proceed();
    }
  }
);


“hello world”.capitalize()
// “Hello world”


“hello world”.capitalize(true)
// “Hello World”[/code]
래핑할 함수는 항상 첫번째 인자로 기존에 수행할 함수(메서드)를 받아야 합니다. 이후의 인자들은 외부에서 받는 인자입니다. 여기서도 마찬가지로 this가 보존됩니다.

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]