currency.js icon indicating copy to clipboard operation
currency.js copied to clipboard

Easy way to set defaults

Open tennox opened this issue 5 years ago • 6 comments

I'm using this great lib in a bigger project, and I don't want to pass options to all instanciations, so I created a custom override similar to how it's recommended in the babel plugin readme.

But in order to make it work also with instaneceof checks and so on, it got a bit complicated: https://gist.github.com/TeNNoX/92770bba1457de1a221bc5ca1462a6cb

Wouldn't it be possible to just add a currency.setDefaults(...)?

tennox avatar May 21 '20 12:05 tennox

Why not write a decorator and the import that decorator?

Gibbo3771 avatar May 29 '20 00:05 Gibbo3771

import c from "currency.js";

const defaults: c.Options = {
  separator: ",",
  errorOnInvalid: true
};

const currency = (value: c.Any, options: c.Options = defaults) => {
  return c(value, options);
};

Sorry should have included a snippet. This is what I do ^. Technically not a decorator but does the job.

Gibbo3771 avatar May 29 '20 00:05 Gibbo3771

@Gibbo3771 I mean... that's basically what I do - check the gist. I just name it customCurrency and not currency, because otherwise we might auto-import the wrong one when we're not attentive.

Also, with I would have the problem that I need to import the custom currency for instanciation, but the original currency for instanceof checking... Which I worked around by the prototype copying in the gist.

tennox avatar Jun 05 '20 11:06 tennox

I honestly think you're over complicating it. You don't need to do any instanceof checks or override prototypes. Just chuck the code I wrote into a util folder and export it.

Why do you need to instanceof checks? If you have multiple currency instances and their configs are different, again, all you need to do is slap them in a utils folder and export them as named functions.

import c from "currency.js";

const configA: c.Options = {
  separator: ",",
  errorOnInvalid: true
};

const configB: c.Options = {
  separator: ".",
  errorOnInvalid: false
};

export const currencyA = (value: c.Any) => {
  return c(value, configA);
};

export const currencyB = (value: c.Any) => {
  return c(value, configB);
};

Or just create some configs and pass them into the currency method themselves.

Maybe you need to provide an example of why you would need to do an instanceof check?

Gibbo3771 avatar Jun 07 '20 09:06 Gibbo3771

Pretty quick example PR of how to go about this ^

overthemike avatar May 04 '21 17:05 overthemike

@Gibbo3771

Maybe you need to provide an example of why you would need to do an instanceof check?

normal code... To check if an object stored somewhere or passed to a function is a Currency object.

But I'm not involved with the project anymore, just think it's a decent feature which should be possible without a wrapper type that makes typescript usage complicated.

tennox avatar May 04 '21 17:05 tennox