Monday, September 6, 2010

XPages: Helper function for inconsistent API methods - always get an array

Update: I added functionality to convert collections (ArrayList/Vector/etc.) to arrays as well.

// Helper for inconsistent API
// Wrap around @DbLookup/@DbColumn/@Trim/@Unique calls to have an array returned
function $A( object ){
// undefined/null -> empty array
if( typeof object === 'undefined' || object === null ){ return []; }
if( typeof object === 'string' ){ return [ object ]; }

// Collections (Vector/ArrayList/etc) -> convert to Array
if( typeof object.toArray !== 'undefined' ){
return object.toArray();
}

// Array -> return object unharmed
if( object.constructor === Array ){ return object; }

// Return array with object as first item
return [ object ];
}
E.g.
@Unique( 1, 1, 1 ) -> 1
$A( @Unique( 1, 1, 1 ) -> [ 1 ]

@Trim( '', '', 'a', '' ) -> 'a'
$A( @Trim( '', '', 'a', '' ) ) -> ['a']

If IBM fix this inconcistency, your code will not break if you're using the above function. Call it whatever you like. I called it $A from the $A function in MooTools.

Share and enjoy!

2 comments:

David Leedy said...

Great Tip. Thanks for sharing!!

Looking forward to playing with this.

Thomas Adrian said...

Thanks Tommy, just what I needed