_.first = function(array, n) {
if(!n){
return array[0];
} else {
return array.slice(0, n);
}
};
// Like first, but for the last elements. If n is undefined, return just the
// last element.
_.last = function(array, n) {
if(!n){
return array[array.length - 1];
} else {
if(array.length < n){
return array;
}
return array.slice(array.length - n, array.length);
}
};
// Call iterator(value, key, collection) for each element of collection.
// Accepts both arrays and objects.
_.each = function(collection, iterator) {
for(var key in collection){
iterator(collection[key], key, collection);
}
};
// Returns the index at which value can be found in the array, or -1 if value
// is not present in the array.
_.indexOf = function(array, target){
for(var i = 0; i < array.length; i++){
if(array[i] === target){
return i;
}
}
return -1;
};
// Return all elements of an array that pass a truth test.
_.filter = function(collection, iterator) {
var newArray = collection.slice();
for(var i = 0; i < newArray.length; i++){
if(!iterator(newArray[i])){
newArray.splice(i, 1);
}
}
return newArray;
};
// Return all elements of an array that don't pass a truth test.
_.reject = function(collection, iterator) {
var newArray = collection.slice();
for(var i = 0; i < newArray.length; i++){
if(iterator(newArray[i])){
newArray.splice(i, 1);
}
}
return newArray;
};
// Produce a duplicate-free version of the array.
_.uniq = function(array) {
var unique = [];
for(var i = 0; i < array.length; i++){
if(unique.indexOf(array[i]) === -1){
unique.push(array[i]);
}
}
return unique;
};
// Return the results of applying an iterator to each element.
_.map = function(array, iterator) {
var newArray = [];
for(var i = 0; i < array.length; i++){
newArray.push(iterator(array[i]));
}
return newArray;
};
// Takes an array of objects and returns and array of the values of
// a certain property in it. E.g. take an array of people and return
// an array of just their ages
_.pluck = function(array, prop) {
var newK = [];
for(var i = 0; i < array.length; i++){
newK.push(array[i][prop]);
}
return newK;
};
// Calls the method named by methodName on each value in the list.
_.invoke = function(list, methodName, args) {
if(typeof methodName === 'string'){
for(var i = 0; i < list.length; i++){
list[i][methodName].apply(null, args);
}
return list;
} else if(typeof methodName === 'function') {
for(var i = 0; i < list.length; i++){
methodName.apply(list[i], args);
}
return list;
}
};
// Reduces an array or object to a single value by repetitively calling
// iterator(previousValue, item) for each item. previousValue should be
// the return value of the previous iterator call.
_.reduce = function(collection, iterator, initialValue) {
if(!initialValue){
initialValue = 0;
}
for(var i = 0; i < collection.length; i ++){
initialValue = iterator(initialValue, collection[i])
}
return initialValue;
};