Object.groupBy.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. test("length is 2", () => {
  2. expect(Object.groupBy).toHaveLength(2);
  3. });
  4. describe("errors", () => {
  5. test("callback must be a function", () => {
  6. expect(() => {
  7. Object.groupBy([], undefined);
  8. }).toThrowWithMessage(TypeError, "undefined is not a function");
  9. });
  10. test("null or undefined items value", () => {
  11. expect(() => {
  12. Object.groupBy();
  13. }).toThrowWithMessage(TypeError, "undefined cannot be converted to an object");
  14. expect(() => {
  15. Object.groupBy(undefined);
  16. }).toThrowWithMessage(TypeError, "undefined cannot be converted to an object");
  17. expect(() => {
  18. Object.groupBy(null);
  19. }).toThrowWithMessage(TypeError, "null cannot be converted to an object");
  20. });
  21. });
  22. describe("normal behavior", () => {
  23. test("basic functionality", () => {
  24. const array = [1, 2, 3, 4, 5, 6];
  25. const visited = [];
  26. const firstResult = Object.groupBy(array, value => {
  27. visited.push(value);
  28. return value % 2 === 0;
  29. });
  30. expect(visited).toEqual([1, 2, 3, 4, 5, 6]);
  31. expect(firstResult.true).toEqual([2, 4, 6]);
  32. expect(firstResult.false).toEqual([1, 3, 5]);
  33. const firstKeys = Object.keys(firstResult);
  34. expect(firstKeys).toHaveLength(2);
  35. expect(firstKeys[0]).toBe("false");
  36. expect(firstKeys[1]).toBe("true");
  37. const secondResult = Object.groupBy(array, (_, index) => {
  38. return index < array.length / 2;
  39. });
  40. expect(secondResult.true).toEqual([1, 2, 3]);
  41. expect(secondResult.false).toEqual([4, 5, 6]);
  42. const secondKeys = Object.keys(secondResult);
  43. expect(secondKeys).toHaveLength(2);
  44. expect(secondKeys[0]).toBe("true");
  45. expect(secondKeys[1]).toBe("false");
  46. });
  47. test("never calls callback with empty array", () => {
  48. var callbackCalled = 0;
  49. expect(
  50. Object.groupBy([], () => {
  51. callbackCalled++;
  52. })
  53. ).toEqual({});
  54. expect(callbackCalled).toBe(0);
  55. });
  56. test("calls callback once for every item", () => {
  57. var callbackCalled = 0;
  58. const result = Object.groupBy([1, 2, 3], () => {
  59. callbackCalled++;
  60. });
  61. expect(result.undefined).toEqual([1, 2, 3]);
  62. expect(callbackCalled).toBe(3);
  63. });
  64. });