0

My previous related question: How do I intercept sort function within a JS proxy?

Given the proxy:

function sort(customSort) {
  /* Write logs */
  console.log("Intercepted sort")
  return this.sort(customSort);
}
function get( target, prop, receiver ) {
  if (prop === 'sort') {
    /* How to capture custom sort?*/
    return sort.bind(target);
  }
  console.log("Intercepted get")
  return Reflect.get( target, prop, receiver );
}
var handler = {
  get
};
var proxy = new Proxy( new Array(...[7,1,2,3,4,5]), handler );

But now I add a custom sort function:

console.log(proxy.sort((a,b) => .... /* e.g., a-b */))

I cannot understand how to capture the function as to pass it to the proxy sort function. I've tried capturing different arguments in the get function, but can't find the correct one.

Blue Granny
  • 772
  • 1
  • 8
  • 24
  • Don't you just need `function sort()` -> `function sort(a, b)`? I'm not sure what the proxy has to do with this here. – VLAZ Oct 21 '21 at 06:55
  • The proxy I have implemented does some other work as well, that's why I need to proxy – Blue Granny Oct 21 '21 at 06:56
  • You need it *to do what*? I cannot understand what your expectation is here. What are you trying to do? – VLAZ Oct 21 '21 at 07:00
  • The sort function within the proxy does some other work as well, e.g., writes logs. I then need to apply the same sort that the user was trying to do. I.e., the user needs to be oblivious to the proxy. – Blue Granny Oct 21 '21 at 07:01
  • That was definitely not at all apparent to me from the question. You asked how to intercept the `sort()` (and you have) and how to pass arguments. Not how to do custom logic *on top of* a supplied sorting function. If you had example usage it would have been a lot clearer that you expect `arr.sort(mySort)` to actually do `arr.sort(otherSorty(mySort))` – VLAZ Oct 21 '21 at 07:04
  • I have edited the question, please let me know if that is better. Furthermore, if you have the answer please feel free to answer :) – Blue Granny Oct 21 '21 at 07:07
  • 1
    maybe this helps: https://stackoverflow.com/questions/62849907/how-to-sort-only-part-of-array-between-given-indexes/62851253#62851253 – Nina Scholz Oct 21 '21 at 08:23
  • @NinaScholz It does help, thanks! – Blue Granny Oct 21 '21 at 10:35

1 Answers1

0

The solution was similar to: How to sort only part of array? between given indexes

I return a function that accesses argument[0]

function sort(customSort) {
  /* Write logs */
  console.log("Intercepted sort")
  return this.sort(customSort);
}
function get( target, prop, receiver ) {
  if (prop === 'sort') {
    /* How to capture custom sort?*/
     return function(customSort) => {
       return this.sort(customSort || ((a,b) => a-b) )
     }
  }
  console.log("Intercepted get")
  return Reflect.get( target, prop, receiver );
}
Blue Granny
  • 772
  • 1
  • 8
  • 24