Saturday, December 3, 2011

JavaScript Array methods in the latest browsers

Cool and (relatively) new methods on the JavaScript Array object are here in the most recent versions of your favorite browser! More about them on ECMAScript5, MSDN, the IE blog, or Mozilla's documentation. Here's the list that's got me excited:

some & every
Does your callback function return true for any (some) or all (every) of the array's elements?
filter
Filters out elements for which your callback function returns false (in a new copy of the Array).
map
Each element is replaced with the result of it run through your callback function (in a new copy of the Array).
reduce & reduceRight
Your callback is called on each element in the array in sequence (from start to finish in reduce and from finish to start in reduceRight) with the result of the previous callback call passed to the next. Reduce your array to a single value aggregated in any manner you like via your callback function.
forEach
Simply calls your callback passing in each element of your array in turn. I have vague performance concerns as compared to using a normal for loop.
indexOf & lastIndexOf
Finds the first or last (respectively) element in the array that matches the provided value via strict equality operator and returns the index of that element or -1 if there is no such element. Surprisingly, no custom comparison callback method mechanism is provided.

Thursday, December 1, 2011

Bug Spotting: Ctors with default parameters

The following code compiled just fine but did not at all act in the manner I expected:

BOOL CheckForThing(__in CObj *pObj, __in IFigMgr* pFigMgr, __in_opt LPCWSTR url)
{
    BOOL fCheck = FALSE;
    if (SubCheck(pObj))
    {
        ...
I’m calling SubCheck which looks like:
bool SubCheck(const CObj& obj);

Did you spot the bug? As you can see I should be passing in *pObj not pObj since the method takes a const CObj& not a CObj*. But then why does it compile?

It works because CObj has a constructor with all but one param with default values and CObj is derived from IUnknown:

CObj(__in_opt IUnknown * pUnkOuter, __in_opt LPCWSTR pszUrl = NULL);
Accordingly C++ uses this constructor as an implicit conversion operator. So instead of passing in my CObj, I end up creating a new CObj on the stack passing in the CObj I wanted as the outer object which has a number of issues.

The lesson is unless you really want this behavior, don't make constructors with all but 1 or 0 default parameters. If you need to do that consider using the 'explicit' keyword on the constructor.

More info about forcing single argument constructors to be explicit is available on stack overflow.