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

wrap() is wrong #531

Open
mikecann opened this issue Apr 28, 2023 · 1 comment
Open

wrap() is wrong #531

mikecann opened this issue Apr 28, 2023 · 1 comment

Comments

@mikecann
Copy link

#489

import { describe, it, expect } from "@jest/globals";
import { wrap } from "./num";

describe("wrap", () => {
  it("works", () => {
    expect(wrap(11, 10, 25)).toEqual(11);
    expect(wrap(10, 10, 25)).toEqual(10);
    expect(wrap(9, 10, 25)).toEqual(25);
    expect(wrap(24, 10, 25)).toEqual(24);
    expect(wrap(25, 10, 25)).toEqual(25);
    expect(wrap(26, 10, 25)).toEqual(10);
  });
});

If you actually run these test you get different values from what is expected.

@mikecann
Copy link
Author

mikecann commented Apr 28, 2023

This is what I came up with:

/**
 * Wraps a value between min and max, inclusive.
 *
 * e.g.
 *
 *     expect(wrap(0, 0, 9)).toEqual(0);
 *     expect(wrap(1, 0, 9)).toEqual(1);
 *     expect(wrap(9, 0, 9)).toEqual(9);
 *     expect(wrap(10, 0, 9)).toEqual(0);
 *     expect(wrap(11, 0, 9)).toEqual(1);
 *     expect(wrap(19, 0, 9)).toEqual(9);
 *     expect(wrap(10, 0, 9)).toEqual(0);
 *     expect(wrap(-1, 0, 9)).toEqual(9);
 *     expect(wrap(-10, 0, 9)).toEqual(0);
 *     expect(wrap(-11, 0, 9)).toEqual(9);
 *
 *     expect(wrap(10, 10, 19)).toEqual(10);
 *     expect(wrap(11, 10, 19)).toEqual(11);
 *     expect(wrap(19, 10, 19)).toEqual(19);
 *     expect(wrap(20, 10, 19)).toEqual(10);
 *
 * @param value
 * @param min the minimum inclusive value
 * @param max the maximum inclusive value
 */
export function wrap(value: number, min: number, max: number): number {
  const rangeSize = max - min + 1;
  if (value < min) return max - ((min - value - 1) % rangeSize);
  else return min + ((value - min) % rangeSize);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant