Skip to content
This repository has been archived by the owner on Dec 10, 2021. It is now read-only.

feat: improve margin merging with NaN and null #159

Merged
merged 1 commit into from
May 17, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 13 additions & 8 deletions packages/superset-ui-dimension/src/mergeMargin.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,24 @@
import { Margin } from './types';

function mergeOneSide(a: number = 0, b: number = 0, operation: (a: number, b: number) => number) {
if (Number.isNaN(a) || a === null) return b;
else if (Number.isNaN(b) || b === null) return a;

return operation(a, b);
}

export default function mergeMargin(
margin1: Partial<Margin> = {},
margin2: Partial<Margin> = {},
mode: 'expand' | 'shrink' = 'expand',
) {
const { top = 0, left = 0, bottom = 0, right = 0 } = margin1;
const { top: top2 = 0, left: left2 = 0, bottom: bottom2 = 0, right: right2 = 0 } = margin2;

const func = mode === 'expand' ? Math.max : Math.min;
const { top, left, bottom, right } = margin1;
const operation = mode === 'expand' ? Math.max : Math.min;

return {
bottom: func(bottom, bottom2),
left: func(left, left2),
right: func(right, right2),
top: func(top, top2),
bottom: mergeOneSide(bottom, margin2.bottom, operation),
left: mergeOneSide(left, margin2.left, operation),
right: mergeOneSide(right, margin2.right, operation),
top: mergeOneSide(top, margin2.top, operation),
};
}
24 changes: 24 additions & 0 deletions packages/superset-ui-dimension/test/mergeMargin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,4 +163,28 @@ describe('mergeMargin(margin1, margin2, mode?)', () => {
right: -1,
});
});
it('if there are NaN or null, use another value', () => {
expect(
mergeMargin(
// @ts-ignore to let us pass `null` for testing
{
top: 10,
left: null,
bottom: 20,
right: NaN,
},
{
top: NaN,
left: 30,
bottom: null,
right: 40,
},
),
).toEqual({
top: 10,
left: 30,
bottom: 20,
right: 40,
});
});
});