UNPKG

remeda

Version:

A utility library for JavaScript and Typescript.

1 lines 2.44 kB
{"version":3,"file":"withPrecision-BWCostXm.cjs","names":[],"sources":["../src/internal/withPrecision.ts"],"sourcesContent":["// ECMAScript doesn't support more decimal places than 15 anyways,\n// so supporting higher values doesn't make a lot of sense,\n// Considering Number.MAX_SAFE_INTEGER < 10**16, we can use -15\n// for the negative precision limit, too.\nconst MAX_PRECISION = 15;\n\nconst RADIX = 10;\n\nexport const withPrecision =\n (roundingFn: (value: number) => number) =>\n (value: number, precision: number): number => {\n if (precision === 0) {\n return roundingFn(value);\n }\n\n if (!Number.isInteger(precision)) {\n throw new TypeError(\n `precision must be an integer: ${precision.toString()}`,\n );\n }\n\n if (precision > MAX_PRECISION || precision < -MAX_PRECISION) {\n throw new RangeError(\"precision must be between -15 and 15\");\n }\n\n if (Number.isNaN(value) || !Number.isFinite(value)) {\n return roundingFn(value);\n }\n\n const shiftedValue = shiftDecimalPoint(value, precision);\n const rounded = roundingFn(shiftedValue);\n return shiftDecimalPoint(rounded, -precision);\n };\n\n/**\n * Shift a number's decimal point via scientific notation.\n *\n * This takes advantage of the fact that `Number` methods support scientific\n * (e-notation) string natively and avoids working with double-precision\n * floating-point numbers directly, working around their limitations\n * with representing decimal numbers.\n */\nfunction shiftDecimalPoint(value: number, shift: number): number {\n const asString = value.toString();\n const [n, exponent] = asString.split(\"e\");\n\n const shiftedExponent =\n (exponent === undefined ? 0 : Number.parseInt(exponent, RADIX)) + shift;\n\n const shiftedValueAsString = `${n!}e${shiftedExponent.toString()}`;\n\n return Number.parseFloat(shiftedValueAsString);\n}\n"],"mappings":"AAIA,MAAM,EAAgB,GAEhB,EAAQ,GAED,EACV,IACA,EAAe,IAA8B,CAC5C,GAAI,IAAc,EAChB,OAAO,EAAW,EAAM,CAG1B,GAAI,CAAC,OAAO,UAAU,EAAU,CAC9B,MAAU,UACR,iCAAiC,EAAU,UAAU,GACtD,CAGH,GAAI,EAAY,IAAiB,EAAY,IAC3C,MAAU,WAAW,uCAAuC,CAS9D,OANI,OAAO,MAAM,EAAM,EAAI,CAAC,OAAO,SAAS,EAAM,CACzC,EAAW,EAAM,CAKnB,EADS,EADK,EAAkB,EAAO,EAAU,CAChB,CACN,CAAC,EAAU,EAWjD,SAAS,EAAkB,EAAe,EAAuB,CAE/D,GAAM,CAAC,EAAG,GADO,EAAM,UAAU,CACF,MAAM,IAAI,CAKnC,EAAuB,GAAG,EAAG,KAFhC,IAAa,IAAA,GAAY,EAAI,OAAO,SAAS,EAAU,GAAM,EAAI,GAEd,UAAU,GAEhE,OAAO,OAAO,WAAW,EAAqB"}