Skip to content

Commit

Permalink
feat: improve margin merging (apache#159)
Browse files Browse the repository at this point in the history
  • Loading branch information
kristw authored and zhaoyongjie committed Nov 26, 2021
1 parent 58f606b commit aedc1b4
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 8 deletions.
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),
};
}
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,
});
});
});

0 comments on commit aedc1b4

Please sign in to comment.