Permalink
Browse files

[p] added support for error handling

  • Loading branch information...
1 parent 997ea45 commit b12a8cb7ed16215d1a538687be61a42c592691e5 @dscape committed Feb 19, 2012
Showing with 51 additions and 4 deletions.
  1. +2 −0 pattern.js
  2. +24 −0 samples/filter_with_error.test.js
  3. +25 −4 samples/hof.js
View
@@ -2,6 +2,8 @@
var stack = [], arity, DEBUG = process.env.DEBUG;
function log() { if(DEBUG) console.log.apply(this,arguments); }
function match(pattern, value) {
+ if(pattern === Error) {
+ return value && value.name.indexOf('Error') !== -1;}
if(pattern === undefined) return true;
if(typeof pattern === 'object')
return JSON.stringify(pattern) === JSON.stringify(value);
@@ -0,0 +1,24 @@
+/* yeah! */
+var filter = require('./hof').filter_async;
+
+// simulating an async function that could throw
+function gotBang(x, cb) {
+ setTimeout(function() {
+ try {
+ if (x.msg.indexOf('!') !== 1) {
+ process.stderr.write(x.msg);
+ cb(null, x); }
+ } catch (e) { cb(e); }
+ }, Math.ceil(Math.random() * 300));
+}
+
+filter(gotBang,
+ [ {msg: "y"}
+ , {msg: "e"}
+ , {msg: "a"}
+ , {msg: "h"}
+ , {msg: "!"}
+ , null
+ , {msg: "?"}
+ ], [], function(err,data) {
+ if(!err) { console.error('I will never get executed!'); } });
View
@@ -1,10 +1,16 @@
var map = require('../pattern')
, mapa = require('../pattern')
, zip_with = require('../pattern')
- , _, f, ac, l, l1, l2, cb
+ , filtera = require('../pattern')
+ , maybe = require('../pattern')
+ , _, f, ac, l, l1, l2, cb, errcb
;
-// high order functions
+// error handling for conditional execution of functions
+maybe(Error, _, errcb, cb, function (err, data, errcb, cb) { errcb(err); });
+maybe(_, _, errcb, cb, function(err, data, errcb, cb) { cb(data); });
+
+// map
map(f, [], ac, cb,
function map_done(f, l, ac, cb) { return cb(ac); });
map(f, l, ac, cb,
@@ -13,6 +19,7 @@ map(f, l, ac, cb,
map(f, l, ac, cb); // l is now tail
});
+// map with async f, no error possible
mapa(f, [], ac, cb,
function map_done(f, l, ac, cb) { return cb(ac); });
mapa(f, l, ac, cb,
@@ -23,7 +30,20 @@ mapa(f, l, ac, cb,
});
});
-// filter
+// filter with async f
+filtera(f, [], ac, cb, function filter_done(f, l, ac, cb) {
+ return cb(null, ac);
+});
+filtera(f, l, ac, cb, function filter_catch_all(f, l, ac, cb) {
+ var head = l.shift();
+ f(head, function(err, ok) {
+ maybe(err, ok, cb, function (ok) {
+ if (ok) ac.push(head);
+ filtera(f, l, ac, cb); // l is now tail
+ });
+ });
+});
+
// foldl
zip_with(f, [], l2, ac, cb, function emptyl1(f, l1, l2, ac, cb) { cb(ac); });
@@ -33,4 +53,5 @@ zip_with(f, l1, l2, ac, cb, function all(f, l1, l2, ac, cb) {
zip_with(f, l1, l2, ac, cb);
});
-module.exports = { map: map, map_async: mapa, zip_with: zip_with };
+module.exports =
+ { map: map, map_async: mapa, zip_with: zip_with, filter_async: filtera };

0 comments on commit b12a8cb

Please sign in to comment.