建立自己的调用栈

时间:2018-12-08 01:24:06

标签: javascript proxy functional-programming ramda.js

我试图单点拦截对库的所有调用,并在库函数之间共享自定义的调用堆栈(数组)。

这是一个FP库,其中管道/组合许多功能是一种常见的做法。内置调用堆栈可以跟踪所有调用(包含噪音),而我想忽略内部调用,而只是将用户调用记录到库中,并按照自己的意愿在自定义堆栈中手动管理内部调用的跟踪。解决方案的一部分似乎是apply陷阱,但不知道从哪里开始。

// Ramda FP library
// Abbreviate input string: 'some input' -> 'S.I'
const app = R.pipe(R.w, R.x, R.y, R.z)
const output = app('some input')

// Sample actual call stack (including internal calls):
// w -> __w0 -> _t2 -> x -> _x1 -> _x2 -> y -> _y -> z -> _z9

// Desired call stack without internal calls (noise)
// x -> y -> z

如果我在自己的库中有自己的用于调用栈的数据结构,则可以生成以下示例的以下输出:

pipe:    w      ->      x     ->     y    ->    z
    'some input'    ['s','i']   ['S','I']    'S.I'

,如果出现错误:

const output = app('')


// desired output
pipe:  w   ->   x   ->    y   ->    z
      ''       []       Error

Error: Array is empty!

摘要:我需要实现自己的虚拟调用堆栈,该堆栈很聪明,用于向图书馆用户提供有用的数据。考虑到在FP库中,部分应用是常见的用例,使得该问题难以解决。

1 个答案:

答案 0 :(得分:0)

这样的事情如何?

const audit = fnc => (...args) => {
  console.log(`Before call`, args);
  const result = fnc(...args);
  console.log(`Outcome`, result);
  return result;
}

const myPipe = (...args) => {
  const auditedArgs = map(audit, args);
  return pipe(...auditedArgs);
}


export myPipe;

您可以通过运行以下命令检查其是否有效:

myPipe(
  split(' '),
  map(myPipe(
    trim,
    head,
    toUpper)),
  join('.'),
)('some input');

Full example

基于此,您可以使用错误处理包装所有内容,而不是像在示例中那样将内容记录到控制台中-在某种堆栈上推送功能,并在失败时返回其状态。