Lasse Reichstein wrote:
The problem is that there are so many ways you might want to use an
object as a function, not just one. In this case, we want it as a
predicate. In other cases you might want it to return the match as a
string, or as a match. Or you want your generic objects to match
against different properties.
The use-case here is that you have an object and want it to act as a
function in a specific case, and it's driven by the way the object is
used, which is unbounded, not the way the object is defined. You can't
be expected to predict all the ways an object is going to be used, and
create one function representation suiting the all.

For this, you need a function per usage, so the "predicate" function
suggested above is exactly the right level of abstraction.

Well argued. I agree in general.

In this specific case, just a couple of thoughts (not disagreeing):

When I made regexps callable way back when, I chose calling a regexp as short for exec'ing, which creates a match array result. Then I optimized the exec/call built-in to peek into its continuation to see if the result was used only for its boolishness. If so, the built-in would pass a flag parameter to the common internal API for regexp execution to avoid creating the result array, substituting false/true for null/the-array.

One way for generic callback-invoking map, forEach, filter, etc. functions to go: call the .call method of the callback, assuming the callback is a function but enabling non-function objects to delegate to a call method that knows how to invoke them. This is shown at Steve Levithan's XRegExp github readme:

https://github.com/slevithan/XRegExp

// XRegExp regexes get call and apply methods
// To demonstrate, let's first create the function we'll be using...
function  filter(array,  fn)  {
    var  res  =  [];
    array.forEach(function  (el)  {if  (fn.call(null,  el))  res.push(el);});
    return  res;
}
// Now we can filter arrays using functions and regexes
filter(['a',  'ba',  'ab',  'b'],  XRegExp('^a'));  // ->  ['a', 'ab']


This may be optimization-hostile at first glance, but VMs optimize call and apply with special caching and inlining.

The bad old hardcoded-per-builtin optimization to avoid creating a useless-except-for-its-boolish-value result array is ideally generalized via inlining and type inference to cover many such results-allocating functions that are sometimes or often called just to test that they return non-null.

 /be

_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to