1
\$\begingroup\$

I have a library with two methods: one takes an object and vararg strings, the other takes a default value as well.

They are currently implemented as:

export default class koalaesce {
 static get(base, ...steps) {
 return koalaesce.getDefault(base, null, ...steps);
 }
 static getOrThrow(base, ...steps) {
 return // long impl;
 }
 static getDefault(base, def, ...steps) {
 try {
 return koalaesce.getOrThrow(base, ...steps);
 } catch (e) {
 if (e.constructor === MissingLinkError || e.constructor === NullLinkError) {
 return def;
 } else {
 throw e;
 }
 }
 }
}

and would be called like:

get(obj, "foo", "bar", "baz")
getDefault(obj, 9, "foo", "bar", "baz")

I feel weird splitting up the base and args with the default value, but I'm not sure if putting the default value first is appropriate:

getDefault(9, obj, "foo", "bar", "baz")

Since the base object and args are related, this seems more reasonable, but I don't think I've seen the default value come first in a case like this (most often, they come last, but that and varargs seems like lousy API design).

Is there an idiomatic way to do this, for Javascript or in general? If so, what is the reasoning behind that?

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Mar 4, 2015 at 17:43
\$\endgroup\$
1
  • \$\begingroup\$ This question is very much about real code, from the koalaesce library. I'm currently focused on the API, over the implementation. \$\endgroup\$ Commented Mar 4, 2015 at 18:18

1 Answer 1

1
\$\begingroup\$

Yes, varargs and default args obviously conflict, so choose either. I think the API as it is, with two functions, is fine and it's a good way to distinguish the two cases. And I wouldn't expect the default value to go first in any case.

You could also consider not using varargs, right? So getOrThrow(base, steps, default), using an array for steps instead.

answered Mar 6, 2015 at 12:49
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.