1

I have the following functional logic code:

const trans = {}

trans['toCssClass'] = (someListing) => {
     // <-- someListing here is undefined
    console.log(someListing)
    someListing.a = someListing.a ? 'nonapproved' : ''
    someListing.d = someListing.d ? '' : 'deactivated'
}

Because I have many functions alike, (that accept someListing which is either a document or a list of documents, I would like to accept both (object or array).

So I found a way to trace all calls of trans object functions:

function traceMethodCalls(obj) {
    let handler = {
        get(target, propKey, receiver) {
            const origMethod = target[propKey]
            
            return (args) => {
                if (Array.isArray(args))
                    args.forEach(arg => {
                        console.log(arg)
                        origMethod.apply(this, arg)
                    })
                else
                    origMethod.apply(this, args) // <-- args here is defined
            }
        }
    }
    return new Proxy(obj, handler)
}

export default traceMethodCalls(trans)

The call is as simple as

const ob = {a: true, d: true}
transformer['toCssClass']([ob])

It does have the way up to the target function, except that the argument is undefined !

Edit: solution in this answer

user3840170
  • 26,597
  • 4
  • 30
  • 62
BenGee23
  • 43
  • 6
  • `if (Array.isArray(args))`, then you _want_ `origMethod.apply(this, args)`. And `origMethod.apply(this, arg)` only makes sense if `arg` itself is also an Array. Your logic is backwards. Read the [documentation](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/apply#parameters). – Sebastian Simon Jan 15 '23 at 18:20

0 Answers0