impr: add function to merge partial config onto default config

This commit is contained in:
Miodec 2024-02-07 17:09:02 +01:00
parent 848e851973
commit 4bbe321dfe
2 changed files with 53 additions and 1 deletions

View file

@ -0,0 +1,39 @@
import { mergeWithDefaultConfig } from "../../src/ts/config";
import DefaultConfig from "../../src/ts/constants/default-config";
describe("config.ts", () => {
describe("mergeWithDefaultConfig", () => {
it("should carry over properties from the default config", () => {
const partialConfig = {} as Partial<MonkeyTypes.Config>;
const result = mergeWithDefaultConfig(partialConfig);
expect(result).toEqual(expect.objectContaining(DefaultConfig));
for (const [key, value] of Object.entries(DefaultConfig)) {
expect(result).toHaveProperty(key, value);
}
});
it("should not merge properties which are not in the default config (legacy properties)", () => {
const partialConfig = {
legacy: true,
} as Partial<MonkeyTypes.Config>;
const result = mergeWithDefaultConfig(partialConfig);
expect(result).toEqual(expect.objectContaining(DefaultConfig));
expect(result).not.toHaveProperty("legacy");
});
it("should correctly merge properties of various types", () => {
const partialConfig = {
mode: "quote",
hideExtraLetters: true,
time: 120,
accountChart: ["off", "off", "off", "off"],
} as Partial<MonkeyTypes.Config>;
const result = mergeWithDefaultConfig(partialConfig);
expect(result.mode).toEqual("quote");
expect(result.hideExtraLetters).toEqual(true);
expect(result.time).toEqual(120);
expect(result.accountChart).toEqual(["off", "off", "off", "off"]);
});
});
});

View file

@ -15,7 +15,7 @@ import {
canSetConfigWithCurrentFunboxes,
canSetFunboxWithConfig,
} from "./test/funbox/funbox-validation";
import { reloadAfter } from "./utils/misc";
import { reloadAfter, typedKeys } from "./utils/misc";
export let localStorageConfig: MonkeyTypes.Config;
@ -2026,6 +2026,19 @@ export function getConfigChanges(): MonkeyTypes.PresetConfig {
return configChanges;
}
export function mergeWithDefaultConfig(
config: Partial<MonkeyTypes.Config>
): MonkeyTypes.Config {
const mergedConfig = {} as MonkeyTypes.Config;
for (const key of typedKeys(DefaultConfig)) {
const newValue =
config[key] ?? (DefaultConfig[key] as MonkeyTypes.ConfigValue);
//@ts-ignore cant be bothered to deal with this
mergedConfig[key] = newValue;
}
return mergedConfig;
}
export const loadPromise = new Promise((v) => {
loadDone = v;
});