-1

I'm puzzled by this construction. It's from a published npm module. It seems the author knows his javascript. Versions of it appear several times in the module.

[].concat( opts['boolean'] ).filter( Boolean ).forEach( function( key ){
  flags.bools[key] = true;
});

Since it doesn't modify the original array and also the member 'boolean' is known from the outset, why not just:

opts.boolean.filter(Boolean).forEach(....
5
  • 2
    opts['boolean'] probably isn't an Array, so you can't filter or map over it. Commented Mar 28, 2017 at 19:45
  • 1
    While the author probably wants a shorthand to avoid calling .concat on non-genuine Array objects, the .filter() will keep any truthy values, so if opts.boolean is a plain object, it will be doing flags.bools["[object Object]"] = true;. Maybe the author is OK with that, but it doesn't seem like the best approach. Commented Mar 28, 2017 at 20:01
  • IMO, a better way would be if (Array.isArray(opts.boolean)) { opts.boolean.filter(Boolean).forEach(...) } Commented Mar 28, 2017 at 20:04
  • I guess I should have mentioned that opts.boolean is an optional user supplied value. When present it must be an Array but it may be undefined. Commented Mar 28, 2017 at 20:51
  • I had to look this one up. Boolean called w/o new returns a primitive true/false value depending on the truthiness of the argument. so the .filter returns all truthy entries in opts.boolean Commented Mar 28, 2017 at 20:58

1 Answer 1

0

Maybe because of this:

[].concat(undefined) // => [undefined]

undefined.filter(...) // => ERROR

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.