Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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?

share|improve this question
    
This question is very much about real code, from the koalaesce library. I'm currently focused on the API, over the implementation. –  ssube Mar 4 at 18:18

1 Answer 1

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.