How to determine which arguments have already been passed to the partial lodash function?

Let's say I pass different data to a function in different places to get around some legacy solutions / code.

var partialFunction;
if(thisSituationIsCrazy(data, value)) {
    partialFunction = _.partial(originalFunciton, data)
} else {
    partialFunction = _.partialRight(originalFunction, value)
}

Is there a way to determine which values ​​were actually passed and in which place in the function? This is for debugging purposes only.

I hope for something like partialFunction.argumentsor some that will shed some light on where he got to, because the real situation is more complicated than my example.

I have not seen a way to do this based on lodash docs , as well as the source code . I also have not seen this on any blogs on this subject.

+4
source share
2 answers

Higher order functions (HOF), .

HOF - , , " " .

//now a demo of what you want
function greet(a, b, c) {
  return a + ' ' + b + ' ' + c;
}

function trackArguments(fn, ctx) {
  const trackedArgs = [];
  function tracker(partialFn, ...args) {
     trackedArgs.push(...args);
     const res = fn.call(ctx, partialFn, ...args);
     res.trackedArgs = trackedArgs;
     return res;
  }
  tracker.trackedArgs = trackedArgs;
  return tracker
}
 
const trackedPartial = trackArguments(_.partial, _);

var sayHelloTo = trackedPartial(greet, 'hello', 'Stack');

console.log('Arguments passed already:', sayHelloTo.trackedArgs);

console.log('Execution works perfctly:', sayHelloTo('Overflow'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
+1

, , , , .

, , :

//your wrapping inside a IIFE (Immediately-Invoked Function Expression)
(function() {
    var _partial = _.partial,
        _partialRight = _.partialRight;
    _.partial = function() {
        var args = Array.from(arguments).slice(1),
            ret = _partial.apply(_, arguments);
        ret.args = args;
        return ret;
    }

    _.partialRight = function() {
        var args = Array.from(arguments).slice(1),
            ret = _partialRight.apply(_, arguments);
        ret.args = args;
        return ret;
    }
})();

//now a demo of what you want
function greet(a, b, c) {
  return a + ' ' + b + ' ' + c;
}
 
var sayHelloTo = _.partial(greet, 'hello', 'Stack');
console.log('Arguments passed already:', sayHelloTo.args);
console.log('Execution works perfctly:', sayHelloTo('Overflow'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
+1

Source: https://habr.com/ru/post/1684371/


All Articles