Skip to content

Commit

Permalink
feat(core): add utility for merge config function
Browse files Browse the repository at this point in the history
  • Loading branch information
TomokiMiyauci committed Mar 31, 2022
1 parent 6c70c5a commit 920edd7
Show file tree
Hide file tree
Showing 4 changed files with 89 additions and 0 deletions.
1 change: 1 addition & 0 deletions core/deps.ts
Expand Up @@ -51,6 +51,7 @@ export function prop<
export type Arrayable<T> = T | T[];
export { deepMerge } from "https://deno.land/std@0.122.0/collections/deep_merge.ts";
export { distinctBy } from "https://deno.land/std@0.125.0/collections/distinct_by.ts";
export { mapEntries } from "https://deno.land/std@0.125.0/collections/map_entries.ts";
export function wrap<T>(val: T): T extends any[] ? T : T[] {
return Array.isArray(val) ? val as never : [val] as never;
}
Expand Down
1 change: 1 addition & 0 deletions core/mod.ts
Expand Up @@ -10,3 +10,4 @@ export * from "./resolve.ts";
export * from "./types.ts";
export * from "./ast.ts";
export * from "./transform.ts";
export * from "./util.ts";
23 changes: 23 additions & 0 deletions core/util.ts
@@ -0,0 +1,23 @@
import { Config } from "./types.ts";
import { deepMerge, mapEntries, wrap } from "./deps.ts";

/** merge two config.
* if it exists arrayable property, the value will wrap array and merge.
*/
export function mergeConfig(a: Config, b: Config): Config {
const arrayables = ["css", "extractor"];

return deepMerge(wrapArray(a, arrayables), wrapArray(b, arrayables), {
arrays: "merge",
});
}

function wrapArray<T extends Record<PropertyKey, unknown>>(
value: T,
keys: string[],
): T {
return mapEntries(value, ([key, value]) => {
const v = keys.includes(key) ? wrap(value) : value;
return [key, v];
}) as T;
}
64 changes: 64 additions & 0 deletions core/util_test.ts
@@ -0,0 +1,64 @@
import { mergeConfig } from "./util.ts";
import { anyFunction, expect, ParamReturn } from "../dev_deps.ts";

Deno.test("mergeConfig", () => {
const table: ParamReturn<typeof mergeConfig>[] = [
[{}, {}, {}],
[
{
css: {},
},
{ css: {} },
{
css: [{}, {}],
},
],
[
{
css: { a: {} },
},
{ css: [{}] },
{
css: [{ a: {} }, {}],
},
],
[
{
css: { a: {} },
},
{
cssMap: {
block: { display: "block" },
},
},
{
cssMap: {
block: { display: "block" },
},
css: [{ a: {} }],
},
],
[
{
preset: [{
name: "preset1",
fn: () => ({}),
}],
},
{
preset: [{
name: "preset2",
fn: () => ({}),
}],
},
{
preset: [
{ name: "preset1", fn: anyFunction() as any },
{ name: "preset2", fn: anyFunction() as any },
],
},
],
];

table.forEach(([a, b, result]) => expect(mergeConfig(a, b)).toEqual(result));
});

0 comments on commit 920edd7

Please sign in to comment.