Today was my first day working with JavaScript and I tried to implement some Linq-like (C#) functions as extension methods.
I'm pretty new to JavaScript and wanted to ask you for checking my functions and tell me, whether they're good and really usable in productive applications. Or maybe, what I could do better. I don't know whether there is already a library for this; it's primarily for learning purposes.
Array.prototype.where = function * (predicate){
for(var i=0; i < this.length; i++){
if (predicate(this[i])) yield this[i];
}
}
Array.prototype.all = function (predicate){
for(var i=0; i < this.length; i++){
if (!predicate(this[i])) return false;
}
return true;
}
Array.prototype.any = function (predicate){
if (predicate == null) return this.length >0;
for(var i=0; i < this.length; i++){
if (predicate(this[i])) return true;
}
return false;
}
Array.prototype.select = function * (predicate){
for(var i=0; i < this.length; i++){
yield predicate(this[i], i);
}
}
Array.prototype.groupby = function (predicate){
var result = {};
for(var i=0; i < this.length; i++){
var key = predicate(this[i]);
if (result[key] == null)
result[key] = Array();
result[key].push(this[i]);
}
return result;
}
Array.prototype.foreach = function (predicate){
for(var i=0; i < this.length; i++){
predicate(this[i]);
}
}
Array.prototype.first_or_default = function (predicate){
if (predicate == null){
return this.length > 0 ? this[0] : null;
}
for(var i=0; i < this.length; i++){
if (predicate(this[i]))
return this[i];
}
return null;
}
Array.prototype.last_or_default = function (predicate){
return this.reverse().first_or_default();
}
Array.prototype.count = function (predicate){
var count = this.length;
if (predicate == null) return count;
for(var i=0; i < this.length; i++){
if (!predicate(this[i])) count-=1;
}
return count;
}
Array.prototype.distinct = function * (predicate){
var already_yielded = []
var has_predicate = predicate != null;
for(var i=0; i < this.length; i++){
var current_element = this[i];
if (!has_predicate){
if (already_yielded.indexOf(current_element) >= 0) continue;
already_yielded.push(current_element);
}else{
if (already_yielded.indexOf(predicate(current_element)) >= 0) continue;
already_yielded.push(predicate(current_element));
}
yield current_element;
}
}