Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[#536] Fix ex.Utils.clamp min/max handling #673

Merged
merged 11 commits into from
Dec 6, 2016
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ This project adheres to [Semantic Versioning](http://semver.org/).
### Added

### Changed
- Changed Util.clamp to use math libraries.

### Deprecated

Expand Down
Empty file added coolnewfiles.txt
Empty file.
4 changes: 2 additions & 2 deletions src/engine/Util/Util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@ module ex.Util {
return outputStr;
}

export function clamp(val, min, max) {
return val <= min ? min : (val >= max ? max : val);
export function clamp(val: number, min: number, max: number) {
return Math.min(Math.max(min, val), max);
}

export function randomInRange(min: number, max: number) : number {
Expand Down
11 changes: 11 additions & 0 deletions src/spec/UtilSpec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,15 @@ describe('Utility functions', () => {
expect(ex.Util.getSideFromVector(ex.Vector.Up)).toBe(ex.Side.Top);
expect(ex.Util.getSideFromVector(ex.Vector.Down)).toBe(ex.Side.Bottom);
});

it('can clamp a number to a maximum and minimum', () => {
expect(ex.Util.clamp(0, 10, 20)).toBe(10);
expect(ex.Util.clamp(15, 10, 20)).toBe(15);
expect(ex.Util.clamp(30, 10, 20)).toBe(20);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add another couple tests for Infinity and -Infinity to test those boundaries?

expect(ex.Util.clamp(-Infinity, 0, 1)).toBe(0);
expect(ex.Util.clamp(Infinity, 0, 1)).toBe(1);
expect(ex.Util.clamp(12, -Infinity, Infinity)).toBe(12);
expect(ex.Util.clamp(12, -Infinity, 100)).toBe(12);
expect(ex.Util.clamp(12, -100, Infinity)).toBe(12);
});
});