elpete / CFCollection

An array wrapper for functional programming
MIT License
6 stars 6 forks source link

.pluck() fails when a key has a null value #28

Open MordantWastrel opened 3 years ago

MordantWastrel commented 3 years ago

I finally got an opportunity to play some with cfcollection a month ago or so and ran into a small issue when dealing with collections that may have null keys. See this example:

var data = [ { 'foo' : 'bar', 'baz' : 'frobozz' }, { 'foo' : 'also bar', 'baz' : javacast( "null", "" ) } ];

var collection = wirebox.getInstance( name = "Collection@cfcollection", initArguments = { collection : data } );

dump( collection.toArray() );

Good so far!

But if you try this:

dump( collection.pluck( 'baz' ) );

It will throw:

Error: the value from key [baz] is NULL, which is the same as not existing in CFML (expression)

on Collection.cfc : 87 (ID: ??, Type: cfml)

Which is this line:

  return item[ keys[ 1 ] ];

This works as a workaround:

   return ( item[ keys[ 1 ] ] ?: '' );

Do you prefer a different solution or shall I submit that as a PR?

elpete commented 3 years ago

You won't be able to use the null coalescing operator (?:) so we can maintain compatibility with older engines. Additionally, I'd prefer to return null rather than an empty string.

Maybe something like

return item.keyExists( keys[ 1 ] ) && !isNull( item[ keys[ 1 ] ] ) ? item[ keys[ 1 ] ] : javacast( "null", "" );
MordantWastrel commented 3 years ago

I like that better as well! I'll play with it and get a patch in.

MordantWastrel commented 3 years ago

FYI, the box.json for CFCollection is pointing to Coldbox 4 and Testbox 2. That's some generous backwards compatibility!

elpete commented 3 years ago

Ha...it is. I've been wanting to modernize this entire module using more of the built-in functional methods in later CFML engines, but it just hasn't happened yet.