Coffeescript Recipe

Array comprehension을 알아보자

Array를 가공해서

또 다른 Array로

Map /w javascript

ECMA6

ECMA5

[{name: "pie", price: 10}, {name: "coffee", price: 5}].map( v=> v.price );
[{name: "pie", price: 10}, {name: "coffee", price: 5}].map(
  function(v) {
    return v.price;
});
[ 10, 5 ]

Result

Array Comprehension /w coffeescript

v.price for v in [{name: "pie", price: 10}, {name: "coffee", price: 5}]

# or

for v in [{name: "pie", price: 10}, {name: "coffee", price: 5}]
  v.price
[ 10, 5 ]

Result

Filter

v.price<10

가격이 10 미만인 것만

Map+Filter /w javascript

ECMA6

ECMA5

[{name: "pie", price:10}, {name: "coffee", price: 5}].filter(
  v => v.price < 10 ).map( v=> v.price );
[{ name: "pie", price: 10 }, { name: "coffee", price: 5 }].filter(function (v) {
  return v.price < 10;
}).map(function (v) {
  return v.price;
});
[ 5 ]

Result

Array Comprehension
+Condition
 /w coffeescript

v.price for v in [
  {name: "pie", price: 10 },{name: "coffee", price: 5 }
] when v.price < 10
[ 5 ]

Result

Map + Filter vs
Array Comprehension

Map + Filter

  • [{name: "pie", price:10}, {name: "coffee", price: 5}].filter(v => v.price < 10 )
    >> [{name: "coffee", price:5}]
  • {name: "pie", price:10}, {name: "coffee", price: 5}].filter(
      v => v.price < 10 ).map( v=> v.price )
    >> [5]
  • Array를 두번 생성
  • Map은 for 보다 느리다
  • map을 먼저하면 경우에 따라 느려짐

Array Comprehension

var i, len, ref, results, v;
ref = [
  {
    name: "pie",
    price: 10
  }, {
    name: "coffee",
    price: 5
  }
];
results = [];
for (i = 0, len = ref.length; i < len; i++) {
  v = ref[i];
  if (v.price < 10) {
    results.push(v.price);
  }
}
v.price for v in [
  {name: "pie", price: 10 },{name: "coffee", price: 5 }
] when v.price < 10

Faster & Memory -Optimized

javascript

One more thing

Array comprehension

/w while loop

regular expression - exec

var fruits = "apple_12\n"+"banana_34\n"+"coconut_56"
var regexp = /[a-z]+_([0-9]+)/g

> regexp.exec(fruits)
["apple_12", "12"]
> regexp.exec(fruits)
["banana_34", "34"]
> regexp.exec(fruits)
["coconut_56", "56"]
> regexp.exec(fruits)
null

var getNumber = function() {
  var result = [];
  while (t=regexp.exec(fruits)) {
    result.push(t[1]);
  }
  return result;
};

> getNumber();
[ '12', '34', '56' ]

while loop in coffeescript

> fruits = "apple_12\nbanana_34\ncoconut_56"
> regexp = /[a-z]+_([0-9]+)/g
> x[1] while x=regexp.exec fruits
[ '12', '34', '56' ]

while loop+when in coffeescript

> fruits = "apple_12\nbanana_34\ncoconut_56"
> regexp = /[a-z]+_([0-9]+)/g
> x[1] while x=regexp.exec fruits when x[1]<50
[ '12', '34' ]

<3 coffeescript

Made with Slides.com