Javascript combinator seek
Wednesday, June 24th, 2009Jsgoo.js library is leaning towards functional ( FP ) style of programming. Besides the typical map, reduce and filter I added function I called seek. You can get the same result with reduce (this is sort of optimisation on a subset of reduce) but seek can exit iteration of sequence once it finds it’s return value, while reduce usually iterates whole to reduce it to a return value.
It’s definition goes like this:
seek: function (f, arr) {
for (var i = 0; i < arr.length; i++) { var t = f(arr[i], i); if (t) return t; }
return false;
}
A simple example of usage is function has. It checks if a value is in a sequence.
has: function (n, arr) {
return this.seek(function(e, i){ return e == n; }, arr);
}
It can also be used in unpure manners to modify the data instead of just returning it. We use it in Data Resources part to do select, update, delete by Id:
deleteById: function (data, id) {
return jsGooC.seek(function(x, i){ if (x.id==id){ data.splice(i, 1); return true } else { return false } }, data);
},
updateById: function (data, unit) {
return jsGooC.seek(function(x, i){ if (x.id==unit.id){ data[i] = unit; return true } else { return false } }, data);
}
Perhaps the most interesting use of it in jsgoo itself is the equal function. It tests if two values (data structures) are equal. In JavaScript == doesn’t check for equality on objects and arrays:
equal: function (o1, o2) {
return ! (
o1 instanceof Array && o2 instanceof Array ||
o1 instanceof Object && o2 instanceof Object ?
jsgCore.seek( function ( o, i ) { return ! jsgCore.equal(o, o2[i] ) }, o1 )
: o1 != o2
);
}
Next time I will present how related seek functions can be used to elegantly traverse HTML DOM itself.
Related articles by Zemanta
- Unimpressed by NodeIterator (ejohn.org)
- An introduction to functional programming (geeksaresexy.net)
- Speeding up your JavaScript: Part 3 and 4 (ajaxian.com)
- From Imperative to Functional – Transposing Maps (codebetter.com)
![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=fe8f13f0-a55c-4687-afef-9f2d8a859230)
