Files
gun/src/map.js
2017-10-16 01:10:23 -07:00

38 lines
1.2 KiB
JavaScript

var Gun = require('./index');
Gun.chain.map = function(cb, opt, t){
var gun = this, cat = gun._, chain;
if(!cb){
if(chain = cat.fields){ return chain }
chain = cat.fields = gun.chain();
chain._.val = gun.back('val');
chain._.MAPOF = cat.soul;
gun.on('in', map, chain._);
return chain;
}
Gun.log.once("mapfn", "Map functions are experimental, their behavior and API may change moving forward. Please play with it and report bugs and ideas on how to improve it.");
chain = gun.chain();
gun.map().on(function(data, key, at, ev){
var next = (cb||noop).call(this, data, key, at, ev);
if(u === next){ return }
if(Gun.is(next)){
chain._.on('in', next._);
return;
}
chain._.on('in', {get: key, put: next, gun: chain});
});
return chain;
}
function map(msg){
if(!msg.put || Gun.val.is(msg.put)){ return }
if(this.as.val){ this.off() } // TODO: Ugly hack!
obj_map(msg.put, each, {at: this.as, msg: msg});
this.to.next(msg);
}
function each(v,f){
if(n_ === f){ return }
var msg = this.msg, gun = msg.gun, at = this.at, tmp = (gun.get(f)._);
(tmp.echo || (tmp.echo = {}))[at.id] = at;
}
var obj_map = Gun.obj.map, noop = function(){}, event = {stun: noop, off: noop}, n_ = Gun.node._, u;