underscore playground

by Mi Ku

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
<div id="content">

</div>

JavaScript

var data = [{
	"id": "1",
  "type": "CDFRY"
},
{
	"id": "2",
  "type": "CDFRY"
},
{
	"id": "3",
  "type": "PRLCK"
},
{
	"id": "4",
  "type": "CDFRY"
},
{
	"id": "5",
  "type": "CDFRY"
},
{
	"id": "6",
  "type": "CDFRY"
},
{
	"id": "7",
  "type": "CDFRY"
},
{
	"id": "8",
  "type": "PRUNK"
},
{
	"id": "9",
  "type": "CDFRY"
},
{
	"id": "10",
  "type": "CDFRY"
}]

console.time();
//for (; i < 1000; i++) {
  var b = _.chain(data).filter(function(item) {
    return ['PRLCK', 'PRUNK'].indexOf(item.type) !== -1;
  }).first(5).value();
//}
console.timeEnd();

console.time();
//for (; i < 1000; i++) {
  var b = [];
  _.find(data, function(item) {
    if (_.contains(['PRLCK', 'PRUNK'], item.type)) {
      b.push(item);
      if (b.length === 5) {
        return b;
      }
    }
  });
//}
console.timeEnd();

console.time();
//for (; i < 1000; i++) {
  var b = [];
  for (var i = 0; i < data.length; i++) {
    if (['PRLCK', 'PRUNK'].indexOf(data[i].type) >= 0) {
      b.push(data[i]);
      if (b.length === 5) {
        break;
      }
    }
  }
//}
console.timeEnd();

//console.log(b);