Skip to content

Commit

Permalink
feat(utilities): add percentage helper
Browse files Browse the repository at this point in the history
This provides the user wiht a curried helper function. The first parameter is the percentage of 100
which we want to calculate the second is the total value so for example if we would like to calulate
30 percent of 1024 we would write `percentage(30, 1024)` or `percentage(30)(1024)`

Close DCOS-38640
  • Loading branch information
Poltergeist committed Jul 6, 2018
1 parent 016bae6 commit 3f133ce
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
17 changes: 17 additions & 0 deletions packages/utilities/components/percentage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
function calculate(a, b) {
return (b / 100) * a;
}

function percentage(a?: number, b?: number) {
if (arguments.length === 0) {
return percentage;
}
if (arguments.length === 1) {
return b => {
return calculate(a, b);
};
}
return calculate(a, b);
}

export default percentage;
1 change: 1 addition & 0 deletions packages/utilities/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { default as min } from "./components/min";
export { default as max } from "./components/max";
export { default as percentage } from "./components/percentage";
15 changes: 15 additions & 0 deletions packages/utilities/tests/percentage.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { default as percentage } from "../components/percentage";

describe("percentage", () => {
it("returns percentage of total", () => {
expect(percentage(30, 100)).toEqual(30);
});

it("returns function if only percentage is provided", () => {
expect(typeof percentage(30)).toBe("function");
});

it("returns calculates the percentage from curried function", () => {
expect(percentage(30)(100)).toEqual(30);
});
});

0 comments on commit 3f133ce

Please sign in to comment.