0

I need to construct a function, which takes a black-box one-argument function as an argument. And I need to know, how many times the black-box function uses its argument

Example signature:

function argCounter(fn) {
  return (arg) => {
    let argCalls = 0

    ...

    fn(arg)

    return argCalls
  }
}

Example use:

const fn1 = argCounter(obj => {
  return obj
}

fn1() // 1

const fn2 = argCounter(obj => {
  obj; obj; obj;
  return obj
}

fn2() // 4

I know about JS Proxy, but it only gives me the ability to count how many times an object's methods or attributes have been called. Unfortunately, I couldn't determine, how to use JS Proxy to count, how many times the object itself has been used.

3
  • 2
    A black box is a black box, you can't look inside. If it's not completely black, please tell us what you do know about the function. What do you need this for? Commented Oct 19, 2024 at 21:21
  • possibly Proxy? just a usage cannot be tracked, maybe get values returned via getObj? Commented Oct 19, 2024 at 21:47
  • How do you want to handle the case where inside of a blackbox function the single argument gets assigned to another constant where the latter than is going to be used instead ... e,g. ... const fn2 = argCounter(obj => { const ref = obj; ref; ref; ref; return obj; });? The only way anyhow was to stringify the blackbox-function and pray that whatever is the result can be parsed without error. Thus one actually does not want to go that path. Commented Oct 19, 2024 at 23:07

1 Answer 1

2

This is not possible. There is no hook that is called when a value is referred to.

Notice that this also is subject to optimisation by the engine. The example you gave (obj => { obj; obj; obj; return obj }) is totally equivalent to obj => obj in behaviour.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.