Skip to content

Commit

Permalink
Use deep copy instead of shallow copy for the undercut strategy
Browse files Browse the repository at this point in the history
  • Loading branch information
tiagofilipenunes committed Jan 17, 2024
1 parent 9a3e410 commit cbeab79
Showing 1 changed file with 42 additions and 20 deletions.
62 changes: 42 additions & 20 deletions src/libs/modals/modals/ModalDuplicateStrategy/utils.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,54 @@
import type { Strategy } from 'libs/queries';
import { SafeDecimal } from 'libs/safedecimal';

const replaceDecimal = (key: string, value: any) => {
if (value instanceof SafeDecimal)
return { __type__: 'SafeDecimal', value: value.toString() };
return value;
};
const reviveDecimal = (key: string, value: any) => {
if (
typeof value === 'object' &&
value !== null &&
value['__type__'] === 'SafeDecimal'
)
return new SafeDecimal(value.value);
return value;
};

export const deepCopy = (obj: any): any =>
JSON.parse(JSON.stringify(obj, replaceDecimal), reviveDecimal);

export const getUndercutStrategy = (
strategy: Strategy,
undercutDifference: number
): Strategy => {
const multiplyRate = (rate: string, factor: number) =>
const multiplyByRate = (rate: string, factor: number) =>
new SafeDecimal(rate).times(factor).toString();

const undercutStrategy = {
...strategy,
order0: {
...strategy.order0,
startRate: multiplyRate(
strategy.order0.startRate,
1 + undercutDifference
),
endRate: multiplyRate(strategy.order0.endRate, 1 + undercutDifference),
},
order1: {
...strategy.order1,
startRate: multiplyRate(
strategy.order1.startRate,
1 - undercutDifference
),
endRate: multiplyRate(strategy.order1.endRate, 1 - undercutDifference),
},
};
if (undercutDifference < 0 || undercutDifference > 1)
throw new Error(
'undercutDifference must be less than or equal to 1, and higher than or equal to 0'
);

const undercutStrategy = deepCopy(strategy);

undercutStrategy.order0.startRate = multiplyByRate(
strategy.order0.startRate,
1 + undercutDifference
);
undercutStrategy.order0.endRate = multiplyByRate(
strategy.order0.endRate,
1 + undercutDifference
);
undercutStrategy.order1.startRate = multiplyByRate(
strategy.order1.startRate,
1 - undercutDifference
);
undercutStrategy.order1.endRate = multiplyByRate(
strategy.order1.endRate,
1 - undercutDifference
);

return undercutStrategy;
};

0 comments on commit cbeab79

Please sign in to comment.