Skip to content

Commit

Permalink
Remove decimal.js-light dependency (#1309)
Browse files Browse the repository at this point in the history
  • Loading branch information
emmatown committed Sep 13, 2024
1 parent 351f728 commit f7f659d
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 11 deletions.
5 changes: 5 additions & 0 deletions .changeset/fast-eagles-change.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@keystatic/core': patch
---

Remove unnecessary dependency
1 change: 0 additions & 1 deletion packages/keystatic/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,6 @@
"@urql/exchange-graphcache": "^7.1.2",
"@urql/exchange-persisted": "^4.3.0",
"cookie": "^0.5.0",
"decimal.js-light": "^2.5.1",
"emery": "^1.4.1",
"escape-string-regexp": "^4.0.0",
"fast-deep-equal": "^3.1.3",
Expand Down
28 changes: 28 additions & 0 deletions packages/keystatic/src/form/fields/number/isAtStep.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { isAtStep } from './validateNumber';
import { test, expect } from '@jest/globals';

for (const [value, step] of [
[5, 1],
[5, 0.1],
[5, 0.5],
[5, 5e-3],
[5.1, 0.1],
[5.1, 1e-6],
[5.1, 1e-7],
[5.1, 1e-200],
[300, 3e-200],
]) {
test(`value: ${value}, step: ${step} should be true`, () => {
expect(isAtStep(value, step)).toBe(true);
});
}

for (const [value, step] of [
[5.1, 1],
[5.1, 0.5],
[5.1, 3e-200],
]) {
test(`value: ${value}, step: ${step} should be false`, () => {
expect(isAtStep(value, step)).toBe(false);
});
}
20 changes: 17 additions & 3 deletions packages/keystatic/src/form/fields/number/validateNumber.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import Decimal from 'decimal.js-light';

export function validateNumber(
validation:
| {
Expand Down Expand Up @@ -31,9 +29,25 @@ export function validateNumber(
if (
step !== undefined &&
validation?.validateStep !== undefined &&
new Decimal(value).mod(new Decimal(step)).toNumber() !== 0
!isAtStep(value, step)
) {
return `${label} must be a multiple of ${step}`;
}
}
}

function decimalPlaces(value: number) {
const stringified = value.toString();
const indexOfDecimal = stringified.indexOf('.');
if (indexOfDecimal === -1) {
const indexOfE = stringified.indexOf('e-');
return indexOfE === -1 ? 0 : parseInt(stringified.slice(indexOfE + 2));
}
return stringified.length - indexOfDecimal - 1;
}

export function isAtStep(value: number, step: number) {
const dc = Math.max(decimalPlaces(step), decimalPlaces(value));
const base = Math.pow(10, dc);
return (value * base) % (step * base) === 0;
}
7 changes: 0 additions & 7 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit f7f659d

Please sign in to comment.