aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/Saving.ts
blob: 8017fd10308722aa6c854aece5e6ac6e69a747f6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import type { Grid } from "./Sudoku";

export function save(grid: Grid) {
  const a = document.createElement("a");
  const fileParts = [JSON.stringify(grid)];
  const blob = new Blob(fileParts, { type: 'application/json' }); // the blob
  a.href = URL.createObjectURL(blob);
  a.download = "sudoku-save.json";
  a.click();
}
export function readGridFromFile(f?: File): Promise<string[][] | null> {
  return new Promise(res => {
    let reader = new FileReader();
    reader.onload = e => {
      try {
        if (typeof e.target?.result === "string")
          res(JSON.parse(e.target.result))
        else
          res(null)
      } catch (error) {
        res(null)
      }
    };
    f ? reader.readAsText(f) : f;
  })
}