From 234fcb09c213b9d95aaea8cc13c04e0a6d7c25c9 Mon Sep 17 00:00:00 2001 From: Onyx Azryn Date: Sat, 10 Oct 2020 08:33:24 -0500 Subject: [PATCH] Optimized Reused Values for Loops --- main.js | 22 ++++++++++++++-------- modules/burgs-and-states.js | 14 ++++++++------ modules/cultures-generator.js | 3 ++- modules/names-generator.js | 3 ++- modules/ocean-layers.js | 3 ++- modules/religions-generator.js | 6 ++++-- modules/river-generator.js | 3 ++- modules/routes-generator.js | 7 ++++--- modules/save-and-load.js | 6 ++++-- modules/ui/burg-editor.js | 3 ++- modules/ui/burgs-overview.js | 9 ++++++--- modules/ui/editors.js | 3 ++- modules/ui/elevation-profile.js | 30 +++++++++++++++++++----------- modules/ui/layers.js | 4 ++-- modules/ui/options.js | 3 ++- modules/ui/style.js | 3 ++- modules/ui/tools.js | 3 ++- modules/utils.js | 3 ++- modules/voronoi.js | 17 ++++++++++------- 19 files changed, 91 insertions(+), 54 deletions(-) diff --git a/main.js b/main.js index f0ba76b3..514c0939 100644 --- a/main.js +++ b/main.js @@ -323,10 +323,12 @@ function applyDefaultBiomesSystem() { ]; // parse icons weighted array into a simple array - for (let i=0; i < icons.length; i++) { + var iconsNum = icons.length; + for (let i=0; i < iconsNum; i++) { const parsed = []; for (const icon in icons[i]) { - for (let j = 0; j < icons[i][icon]; j++) {parsed.push(icon);} + var iconVal = icons[i][icon]; + for (let j = 0; j < iconVal; j++) {parsed.push(icon);} } icons[i] = parsed; } @@ -763,7 +765,8 @@ function calculateTemperatures() { const y = grid.points[r][1]; const lat = Math.abs(mapCoordinates.latN - y / graphHeight * mapCoordinates.latT); // [0; 90] const initTemp = tEq - int(lat / 90) * tDelta; - for (let i = r; i < r+grid.cellsX; i++) { + let rPlusCellsX = r+grid.cellsX; + for (let i = r; i < rPlusCellsX; i++) { cells.temp[i] = Math.max(Math.min(initTemp - convertToFriendly(cells.h[i]), 127), -128); } }); @@ -1030,8 +1033,8 @@ function drawCoastline() { // move vertices that are too close to already added ones function relax(vchain, r) { const p = vertices.p, tree = d3.quadtree(); - - for (let i=0; i < vchain.length; i++) { + var vchainLength = vchain.length; + for (let i=0; i < vchainLength; i++) { const v = vchain[i]; let [x, y] = [p[v][0], p[v][1]]; if (i && vchain[i+1] && tree.find(x, y, r) !== undefined) { @@ -1302,7 +1305,8 @@ function addMarkers(number = 1) { const animal = ["Antelope", "Ape", "Badger", "Bear", "Beaver", "Bison", "Boar", "Buffalo", "Cat", "Crane", "Crocodile", "Crow", "Deer", "Dog", "Eagle", "Elk", "Fox", "Goat", "Goose", "Hare", "Hawk", "Heron", "Horse", "Hyena", "Ibis", "Jackal", "Jaguar", "Lark", "Leopard", "Lion", "Mantis", "Marten", "Moose", "Mule", "Narwhal", "Owl", "Panther", "Rat", "Raven", "Rook", "Scorpion", "Shark", "Sheep", "Snake", "Spider", "Swan", "Tiger", "Turtle", "Wolf", "Wolverine", "Camel", "Falcon", "Hound", "Ox"]; const adj = ["New", "Good", "High", "Old", "Great", "Big", "Major", "Happy", "Main", "Huge", "Far", "Beautiful", "Fair", "Prime", "Ancient", "Golden", "Proud", "Lucky", "Fat", "Honest", "Giant", "Distant", "Friendly", "Loud", "Hungry", "Magical", "Superior", "Peaceful", "Frozen", "Divine", "Favorable", "Brave", "Sunny", "Flying"]; - for (let i=0; i < taverns.length && i < count; i++) { + let numberOfTaverns = taverns.length; + for (let i=0; i < numberOfTaverns && i < count; i++) { const cell = taverns.splice(Math.floor(Math.random() * taverns.length), 1); const id = appendMarker(cell, "inn"); const type = P(.3) ? "inn" : "tavern"; @@ -1317,7 +1321,8 @@ function addMarkers(number = 1) { if (lighthouses.length) addMarker("lighthouse", "🚨", 50, 50, 16); const count = Math.ceil(4 * number); - for (let i=0; i < lighthouses.length && i < count; i++) { + let numberOfLighthouses = lighthouses.length; + for (let i=0; i < numberOfLighthouses && i < count; i++) { const cell = lighthouses[i][0], vertex = lighthouses[i][1]; const id = appendMarker(cell, "lighthouse"); const proper = cells.burg[cell] ? pack.burgs[cells.burg[cell]].name : Names.getCulture(cells.culture[cell]); @@ -1330,7 +1335,8 @@ function addMarkers(number = 1) { if (waterfalls.length) addMarker("waterfall", "⟱", 50, 54, 16.5); const count = Math.ceil(3 * number); - for (let i=0; i < waterfalls.length && i < count; i++) { + let numberOfWaterfalls = waterfalls.length; + for (let i=0; i < numberOfWaterfalls && i < count; i++) { const cell = waterfalls[i]; const id = appendMarker(cell, "waterfall"); const proper = cells.burg[cell] ? pack.burgs[cells.burg[cell]].name : Names.getCulture(cells.culture[cell]); diff --git a/modules/burgs-and-states.js b/modules/burgs-and-states.js index abe8e1c7..a0420c58 100644 --- a/modules/burgs-and-states.js +++ b/modules/burgs-and-states.js @@ -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 diff --git a/modules/cultures-generator.js b/modules/cultures-generator.js index 67763f7e..040cdd27 100644 --- a/modules/cultures-generator.js +++ b/modules/cultures-generator.js @@ -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; diff --git a/modules/names-generator.js b/modules/names-generator.js index 32367be1..93375437 100644 --- a/modules/names-generator.js +++ b/modules/names-generator.js @@ -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 diff --git a/modules/ocean-layers.js b/modules/ocean-layers.js index 50f4849c..7a230d05 100644 --- a/modules/ocean-layers.js +++ b/modules/ocean-layers.js @@ -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;}); diff --git a/modules/religions-generator.js b/modules/religions-generator.js index ee22e38e..e92757b3 100644 --- a/modules/religions-generator.js +++ b/modules/religions-generator.js @@ -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; diff --git a/modules/river-generator.js b/modules/river-generator.js index db799885..cc44610a 100644 --- a/modules/river-generator.js +++ b/modules/river-generator.js @@ -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]); diff --git a/modules/routes-generator.js b/modules/routes-generator.js index 2e6d0159..74ce9b3d 100644 --- a/modules/routes-generator.js +++ b/modules/routes-generator.js @@ -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; diff --git a/modules/save-and-load.js b/modules/save-and-load.js index 76f48efd..97b1660d 100644 --- a/modules/save-and-load.js +++ b/modules/save-and-load.js @@ -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([]); diff --git a/modules/ui/burg-editor.js b/modules/ui/burg-editor.js index 0691fa3e..03f074a7 100644 --- a/modules/ui/burg-editor.js +++ b/modules/ui/burg-editor.js @@ -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); diff --git a/modules/ui/burgs-overview.js b/modules/ui/burgs-overview.js index 35d668a6..13f1625e 100644 --- a/modules/ui/burgs-overview.js +++ b/modules/ui/burgs-overview.js @@ -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 += ``; 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); diff --git a/modules/ui/editors.js b/modules/ui/editors.js index 64e615c2..088329f5 100644 --- a/modules/ui/editors.js +++ b/modules/ui/editors.js @@ -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]; diff --git a/modules/ui/elevation-profile.js b/modules/ui/elevation-profile.js index f8b40d29..9ff0f0de 100644 --- a/modules/ui/elevation-profile.js +++ b/modules/ui/elevation-profile.js @@ -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 = 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 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; diff --git a/modules/ui/layers.js b/modules/ui/layers.js index 9be15346..4e32784d 100644 --- a/modules/ui/layers.js +++ b/modules/ui/layers.js @@ -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]; diff --git a/modules/ui/options.js b/modules/ui/options.js index 60eed024..c461e59d 100644 --- a/modules/ui/options.js +++ b/modules/ui/options.js @@ -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"); diff --git a/modules/ui/style.js b/modules/ui/style.js index 2cb1dcaf..db85fe8a 100644 --- a/modules/ui/style.js +++ b/modules/ui/style.js @@ -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, " "); diff --git a/modules/ui/tools.js b/modules/ui/tools.js index 066eda0b..0f1a14e7 100644 --- a/modules/ui/tools.js +++ b/modules/ui/tools.js @@ -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]; diff --git a/modules/utils.js b/modules/utils.js index 3c8d5f6a..50d768fb 100644 --- a/modules/utils.js +++ b/modules/utils.js @@ -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); } }; diff --git a/modules/voronoi.js b/modules/voronoi.js index f7b82292..ba0d29ac 100644 --- a/modules/voronoi.js +++ b/modules/voronoi.js @@ -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))) ]; }
IdCurrent nameNew Name