test: cultureSets to have executable sort functions

This commit is contained in:
max 2022-08-01 23:06:48 +03:00
parent f692f8dfbf
commit 7131a570f4
7 changed files with 362 additions and 7 deletions

View file

@ -0,0 +1,40 @@
import {vi, describe, it, expect} from "vitest";
vi.stubGlobal("Names", {
getBase: () => 0,
getBaseShort: () => "TestName"
});
vi.stubGlobal("COA", {
getRandomShield: () => "TestShield"
});
import {cultureSets, DEFAULT_SORT_STRING} from "./cultureSets";
const supportedMethods = ["score", "temp", "biome", "oceanCoast", "coastDist", "height", "suitability"];
const sortingMethodsMock = Object.fromEntries(supportedMethods.map(method => [method, () => 0]));
const cellIdsMock = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
describe("cultureSets", () => {
it("have executable sort function strings", () => {
const culturesNumber = 1;
Object.values(cultureSets).map(getCultureSet => {
const culturesData = getCultureSet(culturesNumber);
culturesData.forEach(cultureData => {
const sortingString = cultureData.sort || DEFAULT_SORT_STRING;
const allSortingMethods = `{${Object.keys(sortingMethodsMock).join(", ")}}`;
const sortFn = new Function(allSortingMethods, "return " + sortingString);
const comparator = () => {
const cellA = sortFn(sortingMethodsMock);
const cellB = sortFn(sortingMethodsMock);
return cellB - cellA;
};
const sorted = Array.from(cellIdsMock).sort(comparator);
expect(sorted).toEqual(cellIdsMock);
});
});
});
});

View file

@ -18,7 +18,7 @@ interface ICultureConfig {
base: number; // NB id
chance: number; // selection chance [0, 1]
shield: string; // emblem type name
sort?: string; // cells sorting function to place culture center
sort?: string; // string to create a function to compare cells and place culture center
}
const world = () => [
@ -401,3 +401,5 @@ export const cultureSets: {[K in TCultureSetName]: (culturesNumber: number) => I
darkFantasy,
random
};
export const DEFAULT_SORT_STRING = "score()";

View file

@ -1,4 +1,4 @@
export const DEBUG = Boolean(localStorage.getItem("debug"));
export const DEBUG = globalThis.localStorage && Boolean(localStorage.getItem("debug"));
export const INFO = DEBUG || !PRODUCTION;
export const TIME = DEBUG || !PRODUCTION;
export const WARN = true;

View file

@ -1,7 +1,7 @@
import * as d3 from "d3";
import FlatQueue from "flatqueue";
import {cultureSets, TCultureSetName} from "config/cultureSets";
import {cultureSets, DEFAULT_SORT_STRING, TCultureSetName} from "config/cultureSets";
import {
DISTANCE_FIELD,
ELEVATION,
@ -64,7 +64,7 @@ export const generateCultures = function (
const definedCultures: ICulture[] = culturesData.map((cultureData, index) => {
const {name, sort} = cultureData;
const center = placeCenter(sort || "n");
const center = placeCenter(sort || DEFAULT_SORT_STRING);
const base = checkNamesbase(cultureData.base);
const color = colors[index];
const type = defineCultureType(center);