rjrodger / patrun

A fast pattern matcher on JavaScript object properties.
MIT License
143 stars 19 forks source link

Deeply nested patterns #10

Closed AdrianRossouw closed 8 years ago

AdrianRossouw commented 8 years ago

I had a situation where it would have been convenient to match on a pattern that was 2-3 levels deep, and it occurred to me that it might actually be really easy to do this with the current code.

It should be possible to just recursively reduce the objects/patterns into a flat representation, and the existing rules should be sufficient to match on that.


leafReduce({  a: 1,  b: { c: 2,  d: {  e: 'string'  } } });

// outputs - { a: 1, 'b.c': 2, 'b.d.e': 'string' }

// first pass at the reducer.
function leafReduce(pattern) {
   var result = {};
   _.reduce(pattern, _reduce, []);
   return result;
   function _reduce(m, v, k) {
      m.push(k);
      if (!_.isObject(v)) {
        result[m.join('.')] = v;
      } else {
        _.reduce(v, _reduce, m);
      }
      m.pop();
      return m;
   }
}

The one question is what to do about arrays tho.

rjrodger commented 8 years ago

Perfectly valid use-case, and I feel this belongs in a deep-patrun module - let's abide by the spirit of Node and keep this one small and tight.

jmatsushita commented 7 years ago

Hi there, was deep-patrun ever created? How hard would it be if it did, to plug it instead of patrun in seneca?

jmatsushita commented 7 years ago

Looks like what I wanted was in fact https://github.com/rjrodger/parambulator and https://github.com/senecajs/seneca-parambulator for payload validation (rather than seneca role/cmd pattern matching).

jmatsushita commented 7 years ago

Or https://github.com/senecajs/seneca-joi