Optimized Reused Values for Loops

This commit is contained in:
Onyx Azryn 2020-10-10 08:33:24 -05:00
parent 8ec42ca2e5
commit 234fcb09c2
19 changed files with 91 additions and 54 deletions

View file

@ -112,7 +112,8 @@
let spacing = (graphWidth + graphHeight) / 150 / (burgsNumber ** .7 / 66); // min distance between towns
while (burgsAdded < burgsNumber && spacing > 1) {
for (let i=0; burgsAdded < burgsNumber && i < sorted.length; i++) {
let sortedArrayLength = sorted.length;
for (let i=0; burgsAdded < burgsNumber && i < sortedArrayLength; i++) {
if (cells.burg[sorted[i]]) continue;
const cell = sorted[i], x = cells.p[cell][0], y = cells.p[cell][1];
const s = spacing * gauss(1, .3, .2, 2, 2); // randomize to make placement not uniform
@ -656,18 +657,19 @@
const areaMean = d3.mean(valid.map(s => s.area)); // avarage state area
// generic relations
for (let f=1; f < states.length; f++) {
let numberOfStates = states.length;
for (let f=1; f < numberOfStates; f++) {
if (states[f].removed) continue;
if (states[f].diplomacy.includes("Vassal")) {
// Vassals copy relations from their Suzerains
const suzerain = states[f].diplomacy.indexOf("Vassal");
for (let i=1; i < states.length; i++) {
for (let i=1; i < numberOfStates; i++) {
if (i === f || i === suzerain) continue;
states[f].diplomacy[i] = states[suzerain].diplomacy[i];
if (states[suzerain].diplomacy[i] === "Suzerain") states[f].diplomacy[i] = "Ally";
for (let e=1; e < states.length; e++) {
for (let e=1; e < numberOfStates; e++) {
if (e === f || e === suzerain) continue;
if (states[e].diplomacy[suzerain] === "Suzerain" || states[e].diplomacy[suzerain] === "Vassal") continue;
states[e].diplomacy[f] = states[e].diplomacy[suzerain];
@ -676,7 +678,7 @@
continue;
}
for (let t=f+1; t < states.length; t++) {
for (let t=f+1; t < numberOfStates; t++) {
if (states[t].removed) continue;
if (states[t].diplomacy.includes("Vassal")) {
@ -699,7 +701,7 @@
}
// declare wars
for (let attacker=1; attacker < states.length; attacker++) {
for (let attacker=1; attacker < numberOfStates; attacker++) {
const ad = states[attacker].diplomacy; // attacker relations;
if (states[attacker].removed) continue;
if (!ad.includes("Rival")) continue; // no rivals to attack

View file

@ -115,7 +115,8 @@
function getCode(name) {
const words = name.split(" "), letters = words.join("");
let code = words.length === 2 ? words[0][0]+words[1][0] : letters.slice(0,2);
for (let i=1; i < letters.length-1 && pack.cultures.some(c => c.code === code); i++) {
let numberOfLetters = letters.length;
for (let i=1; i < numberOfLetters-1 && pack.cultures.some(c => c.code === code); i++) {
code = letters[0] + letters[i].toUpperCase();
}
return code;

View file

@ -15,7 +15,8 @@
const basic = !(/[^\u0000-\u007f]/.test(name)); // basic chars and English rules can be applied
// split word into pseudo-syllables
for (let i=-1, syllable = ""; i < name.length; i += (syllable.length||1), syllable = "") {
let nameLength = name.length;
for (let i=-1, syllable = ""; i < nameLength; i += (syllable.length||1), syllable = "") {
let prev = name[i] || ""; // pre-onset letter
let v = 0; // 0 if no vowels in syllable

View file

@ -66,7 +66,8 @@
// Define grid ocean cells type based on distance form land
function markupOcean(limits) {
for (let t = -2; t >= limits[0]-1; t--) {
let limits0 = limits[0];
for (let t = -2; t >= limits0-1; t--) {
for (let i = 0; i < pointsN; i++) {
if (cells.t[i] !== t+1) continue;
cells.c[i].forEach(function(e) {if (!cells.t[e]) cells.t[e] = t;});

View file

@ -13,7 +13,8 @@
// turn weighted array into simple array
const approaches = [];
for (const a in approach) {
for (let j=0; j < approach[a]; j++) {
let approachA = approach[a];
for (let j=0; j < approachA; j++) {
approaches.push(a);
}
}
@ -295,7 +296,8 @@
const name = rawName.replace("Old ", ""); // remove Old prefix
const words = name.split(" "), letters = words.join("");
let code = words.length === 2 ? words[0][0]+words[1][0] : letters.slice(0,2);
for (let i=1; i < letters.length-1 && pack.religions.some(r => r.code === code); i++) {
let numberOfLetters = letters.length;
for (let i=1; i < numberOfLetters-1 && pack.religions.some(r => r.code === code); i++) {
code = letters[0] + letters[i].toUpperCase();
}
return code;

View file

@ -167,7 +167,8 @@
const riverEnhanced = []; // to store enhanced segments
let side = 1; // to control meandring direction
for (let s = 0; s < segments.length; s++) {
let numberOfSegments = segments.length;
for (let s = 0; s < numberOfSegments; s++) {
const sX = segments[s].x, sY = segments[s].y; // segment start coordinates
const c = pack.cells.conf[segments[s].cell] || 0; // if segment is river confluence
riverEnhanced.push([sX, sY, c]);

View file

@ -70,13 +70,14 @@
bodies.forEach(function(f) {
const ports = allPorts.filter(b => b.port === f); // all ports on the same feature
if (ports.length < 2) return;
let numberOfPorts = ports.length;
if (numberOfPorts < 2) return;
for (let s=0; s < ports.length; s++) {
for (let s=0; s < numberOfPorts; s++) {
const source = ports[s].cell;
if (connected[source]) continue;
for (let t=s+1; t < ports.length; t++) {
for (let t=s+1; t < numberOfPorts; t++) {
const target = ports[t].cell;
if (connected[target]) continue;

View file

@ -138,7 +138,8 @@ function inlineStyle(clone) {
const compStyle = window.getComputedStyle(this);
let style = "";
for (let i=0; i < compStyle.length; i++) {
let compStyleLength = compStyle.length;
for (let i=0; i < compStyleLength; i++) {
const key = compStyle[i];
const value = compStyle.getPropertyValue(key);
@ -602,7 +603,8 @@ function parseLoadedData(data) {
biomesData.name = biomes[2].split(",");
// push custom biomes if any
for (let i=biomesData.i.length; i < biomesData.name.length; i++) {
let biomeNamesLength = biomesData.name.length;
for (let i=biomesData.i.length; i < biomeNamesLength; i++) {
biomesData.i.push(biomesData.i.length);
biomesData.iconsDensity.push(0);
biomesData.icons.push([]);

View file

@ -181,7 +181,8 @@ function editBurg(id) {
const basic = group.id === "cities" || group.id === "towns";
const burgsInGroup = [];
for (let i=0; i < group.children.length; i++) {
let numberOfChildren = group.children.length;
for (let i=0; i < numberOfChildren; i++) {
burgsInGroup.push(+group.children[i].dataset.id);
}
const burgsToRemove = burgsInGroup.filter(b => !pack.burgs[b].capital);

View file

@ -422,12 +422,14 @@ function overviewBurgs() {
function importBurgNames(dataLoaded) {
if (!dataLoaded) {tip("Cannot load the file, please check the format", false, "error"); return;}
const data = dataLoaded.split("\r\n");
if (!data.length) {tip("Cannot parse the list, please check the file format", false, "error"); return;}
let dataLength = data.length;
let numberOfBurgs = burgs.length;
if (!dataLength) {tip("Cannot parse the list, please check the file format", false, "error"); return;}
let change = [], message = `Burgs will be renamed as below. Please confirm`;
message += `<table class="overflow-table"><tr><th>Id</th><th>Current name</th><th>New Name</th></tr>`;
const burgs = pack.burgs.filter(b => b.i && !b.removed);
for (let i=0; i < data.length && i <= burgs.length; i++) {
for (let i=0; i < dataLength && i <= numberOfBurgs; i++) {
const v = data[i];
if (!v || !burgs[i] || v == burgs[i].name) continue;
change.push({id:burgs[i].i, name: v});
@ -442,7 +444,8 @@ function overviewBurgs() {
buttons: {
Cancel: function() {$(this).dialog("close");},
Confirm: function() {
for (let i=0; i < change.length; i++) {
let changeLength = change.length;
for (let i=0; i < changeLength; i++) {
const id = change[i].id;
pack.burgs[id].name = change[i].name;
burgLabels.select("[data-id='" + id + "']").text(change[i].name);

View file

@ -620,7 +620,8 @@ function selectIcon(initial, callback) {
];
let row = "";
for (let i=0; i < icons.length; i++) {
let numberOfIcons = icons.length;
for (let i=0; i < numberOfIcons; i++) {
if (i%17 === 0) row = table.insertRow(i/17|0);
const cell = row.insertCell(i%17);
cell.innerHTML = icons[i];

View file

@ -52,7 +52,8 @@ function showElevationProfile(data, routeLen, isRiver) {
let lastBurgCell = 0;
let burgCount = 0;
let chartData = {biome:[], burg:[], cell:[], height:[], mi:1000000, ma:0, mih: 100, mah: 0, points:[]};
for (let i=0, prevB=0, prevH=-1; i <data.length; i++) {
let dataLength = data.length;
for (let i=0, prevB=0, prevH=-1; i < dataLength; i++) {
let cell = data[i];
let h = pack.cells.h[cell];
if (h < 20) h = 20;
@ -93,7 +94,8 @@ function showElevationProfile(data, routeLen, isRiver) {
function downloadCSV() {
let data = "Point,X,Y,Cell,Height,Height value,Population,Burg,Burg population,Biome,Biome color,Culture,Culture color,Religion,Religion color,Province,Province color,State,State color\n"; // headers
for (let k=0; k < chartData.points.length; k++) {
let numberOfPoints = chartData.points.length;
for (let k=0; k < numberOfPoints; k++) {
let cell = chartData.cell[k];
let burg = pack.cells.burg[cell];
let biome = pack.cells.biome[cell];
@ -136,15 +138,16 @@ function showElevationProfile(data, routeLen, isRiver) {
}
function draw() {
let dataLength = data.length;
chartData.points = [];
let heightScale = 100 / parseInt(epScaleRange.value);
heightScale *= .9; // curves cause the heights to go slightly higher, adjust here
const xscale = d3.scaleLinear().domain([0, data.length]).range([0, chartWidth]);
const xscale = d3.scaleLinear().domain([0, dataLength]).range([0, chartWidth]);
const yscale = d3.scaleLinear().domain([0, chartData.ma * heightScale]).range([chartHeight, 0]);
for (let i=0; i<data.length; i++) {
for (let i=0; i < dataLength; i++) {
chartData.points.push([xscale(i) + xOffset, yscale(chartData.height[i]) + yOffset]);
}
@ -157,12 +160,16 @@ function showElevationProfile(data, routeLen, isRiver) {
let colors = getColorScheme();
const landdef = chart.select("defs").append("linearGradient").attr("id", "landdef").attr("x1", "0%").attr("y1", "0%").attr("x2", "0%").attr("y2", "100%");
if (chartData.mah == chartData.mih) {
landdef.append("stop").attr("offset", "0%").attr("style", "stop-color:" + getColor(chartData.mih, colors) + ";stop-opacity:1");
landdef.append("stop").attr("offset", "100%").attr("style", "stop-color:" + getColor(chartData.mah, colors) + ";stop-opacity:1");
let mihChartData = chartData.mih;
let mahChartData = chartData.mah;
if (chartData.mah == mihChartData) {
landdef.append("stop").attr("offset", "0%").attr("style", "stop-color:" + getColor(mihChartData, colors) + ";stop-opacity:1");
landdef.append("stop").attr("offset", "100%").attr("style", "stop-color:" + getColor(mahChartData, colors) + ";stop-opacity:1");
} else {
for (let k=chartData.mah; k >= chartData.mih; k--) {
let perc = 1 - (k - chartData.mih) / (chartData.mah - chartData.mih);
for (let k=mahChartData; k >= mihChartData; k--) {
let perc = 1 - (k - mihChartData) / (mahChartData - mihChartData);
landdef.append("stop").attr("offset", perc*100 + "%").attr("style", "stop-color:" + getColor(k, colors) + ";stop-opacity:1");
}
}
@ -263,13 +270,14 @@ function showElevationProfile(data, routeLen, isRiver) {
const add = 15;
let xwidth = chartData.points[1][0] - chartData.points[0][0];
for (let k=0; k<chartData.points.length; k++) {
let numberOfPoints = chartData.points.length;
for (let k=0; k < numberOfPoints; k++) {
if (chartData.burg[k] > 0) {
let b = chartData.burg[k];
let x1 = chartData.points[k][0]; // left side of graph by default
if (k > 0) x1 += xwidth/2; // center it if not first
if (k == chartData.points.length-1) x1 = chartWidth + xOffset; // right part of graph
if (k == numberOfPoints-1) x1 = chartWidth + xOffset; // right part of graph
y1+=add;
if (y1 >= yOffset) y1 = add;

View file

@ -728,7 +728,7 @@ function drawStates() {
const chain = []; // vertices chain to form a path
let land = vertices.c[start].some(c => cells.h[c] >= 20 && cells.state[c] !== t);
function check(i) {state = cells.state[i]; land = cells.h[i] >= 20;}
for (let i=0, current = start; i === 0 || current !== start && i < 20000; i++) {
const prev = chain[chain.length - 1] ? chain[chain.length - 1][0] : -1; // previous vertex in chain
chain.push([current, state, land]); // add current vertex to sequence
@ -760,7 +760,7 @@ function drawBorders() {
const sUsed = new Array(pack.states.length).fill("").map(a => []);
const pUsed = new Array(pack.provinces.length).fill("").map(a => []);
for (let i=0; i < cells.i.length; i++) {
for (let i=0; i < n; i++) {
if (!cells.state[i]) continue;
const p = cells.province[i];
const s = cells.state[i];

View file

@ -295,7 +295,8 @@ function applyStoredOptions() {
if (localStorage.getItem("distanceUnit")) applyOption(distanceUnitInput, localStorage.getItem("distanceUnit"));
if (localStorage.getItem("heightUnit")) applyOption(heightUnit, localStorage.getItem("heightUnit"));
for (let i=0; i < localStorage.length; i++) {
let localStorageLength = localStorage.length;
for (let i=0; i < localStorageLength; i++) {
const stored = localStorage.key(i), value = localStorage.getItem(stored);
const input = document.getElementById(stored+"Input") || document.getElementById(stored);
const output = document.getElementById(stored+"Output");

View file

@ -1111,7 +1111,8 @@ function addFonts(url) {
// Update font list for Label and Burg Editors
function updateFontOptions() {
styleSelectFont.innerHTML = "";
for (let i=0; i < fonts.length; i++) {
let numberOfFonts = fonts.length;
for (let i=0; i < numberOfFonts; i++) {
const opt = document.createElement('option');
opt.value = i;
const font = fonts[i].split(':')[0].replace(/\+/g, " ");

View file

@ -109,7 +109,8 @@ function regenerateBurgs() {
const burgsCount = manorsInput.value == 1000 ? rn(sorted.length / 5 / (grid.points.length / 10000) ** .8) + states.length : +manorsInput.value + states.length;
const spacing = (graphWidth + graphHeight) / 150 / (burgsCount ** .7 / 66); // base min distance between towns
for (let i=0; i < sorted.length && burgs.length < burgsCount; i++) {
let sortedLength = sorted.length;
for (let i=0; i < sortedLength && burgs.length < burgsCount; i++) {
const id = burgs.length;
const cell = sorted[i];
const x = cells.p[cell][0], y = cells.p[cell][1];

View file

@ -457,7 +457,8 @@ function ra(array) {
function rw(object) {
const array = [];
for (const key in object) {
for (let i=0; i < object[key]; i++) {
let objectKey = object[key];
for (let i=0; i < objectKey; i++) {
array.push(key);
}
};

View file

@ -8,7 +8,8 @@
const cells = {v: [], c: [], b: []}; // voronoi cells: v = cell vertices, c = adjacent cells, b = near-border cell
const vertices = {p: [], v: [], c: []}; // cells vertices: p = vertex coordinates, v = neighboring vertices, c = adjacent cells
for (let e=0; e < delaunay.triangles.length; e++) {
var triangles = delaunay.triangles.length;
for (let e=0; e < triangles; e++) {
const p = delaunay.triangles[nextHalfedge(e)];
if (p < pointsN && !cells.c[p]) {
@ -67,13 +68,15 @@
function prevHalfedge(e) {return (e % 3 === 0) ? e+2 : e-1;}
function circumcenter(a, b, c) {
let ad = a[0]*a[0] + a[1]*a[1],
bd = b[0]*b[0] + b[1]*b[1],
cd = c[0]*c[0] + c[1]*c[1];
let D = 2 * (a[0] * (b[1] - c[1]) + b[0] * (c[1] - a[1]) + c[0] * (a[1] - b[1]));
let a0 = a[0], b0 = b[0], c0 = c[0],
a1 = a[1], b1 = b[1], c1 = c[1];
let ad = a0*a0 + a1*a1,
bd = b0*b0 + b1*b1,
cd = c0*c0 + c1*c1;
let D = 2 * (a0 * (b1 - c1) + b0 * (c1 - a1) + c0 * (a1 - b1));
return [
Math.floor(1/D * (ad * (b[1] - c[1]) + bd * (c[1] - a[1]) + cd * (a[1] - b[1]))),
Math.floor(1/D * (ad * (c[0] - b[0]) + bd * (a[0] - c[0]) + cd * (b[0] - a[0])))
Math.floor(1/D * (ad * (b1 - c1) + bd * (c1 - a1) + cd * (a1 - b1))),
Math.floor(1/D * (ad * (c0 - b0) + bd * (a0 - c0) + cd * (b0 - a0)))
];
}