Skip to content

Commit

Permalink
Fix months not showing up in the correct order
Browse files Browse the repository at this point in the history
  • Loading branch information
Ru Chern Chong committed Nov 14, 2023
1 parent 4741c10 commit e996321
Show file tree
Hide file tree
Showing 5 changed files with 32 additions and 2 deletions.
Binary file modified bun.lockb
Binary file not shown.
5 changes: 3 additions & 2 deletions components/Infographic.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { useState } from "react";
import dynamic from "next/dynamic";
import { ChartData, ChartOptions } from "chart.js";
import { getUniqueMonths } from "@/lib/getUniqueMonths";
import { stringToUniqueColour } from "@/lib/stringToUniqueColour";
import { transformDataToDatasets } from "@/lib/transformDataToDatasets";
import type { Car, ChartDataset, Dataset } from "@/types";
Expand All @@ -25,7 +26,7 @@ export const Infographic = ({ electricCars }: InfographicProps) => {
const [datasets, setDatasets] = useState(initialDatasets);

const data: ChartData<"line"> = {
labels: [...new Set(electricCars.map(({ month }) => month))],
labels: getUniqueMonths(electricCars),
datasets: datasets.filter(({ checked }) => checked),
};

Expand Down Expand Up @@ -94,8 +95,8 @@ export const Infographic = ({ electricCars }: InfographicProps) => {
return (
<div key={key} className="flex items-center gap-2">
<input
type="checkbox"
id={key}
type="checkbox"
value={label}
defaultChecked={checked}
onChange={handleMakeChange(index)}
Expand Down
19 changes: 19 additions & 0 deletions lib/getUniqueMonths.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { getUniqueMonths } from "@/lib/getUniqueMonths";

describe("getUniqueMonths", () => {
it("should return a unique set of dates", () => {
const dates = [
{ key: "2023-04" },
{ key: "2023-04" },
{ key: "2023-04" },
{ key: "2023-01" },
{ key: "2023-02" },
{ key: "2023-03" },
];

const result = ["2023-01", "2023-02", "2023-03", "2023-04"];

expect(getUniqueMonths(dates, "key")).toHaveLength(4);
expect(getUniqueMonths(dates, "key")).toEqual(result);
});
});
9 changes: 9 additions & 0 deletions lib/getUniqueMonths.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { parseISO } from "date-fns";

export const getUniqueMonths = (data: any[], sortKey: string = "month") =>
[...new Set(data.map((item) => item[sortKey]))].sort((a, b) => {
const monthA = parseISO(a);
const monthB = parseISO(b);

return monthA.getTime() - monthB.getTime();
});
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"chart.js": "^4.4.0",
"classnames": "^2.3.2",
"d3": "^7.8.5",
"date-fns": "^2.30.0",
"next": "14.0.0",
"react": "^18",
"react-chartjs-2": "^5.2.0",
Expand Down

0 comments on commit e996321

Please sign in to comment.