Is there a better way of finding solution than using nested loops? - javascript

I am looking to speed up the process of testing all the combinations based on the nested loops in the piece of code included.
I am currently stuck with JavaScript and NodeJS on Windows 10.
Is there a way to compute this using GPU rather than CPU?
var simulations = 0;
for (let i = 10; i <= 20; i++) {
breakStepThree = i;
for (let i = 8; i <= 12; i++) {
historyLevelThree = i;
for (let i = 0; i <= 60; i += 5) {
rateLevelThree = i;
for (let i = 10; i <= 16; i++) {
breakStepTwo = i;
for (let i = 6; i <= 10; i++) {
historyLevelTwo = i;
for (let i = 0; i <= 50; i += 5) {
rateLevelTwo = i;
for (let i = 10; i <= 14; i++) {
breakStepOne = i;
for (let i = 4; i <= 8; i++) {
historyLevelOne = i;
for (let i = 0; i <= 40; i += 5) {
rateLevelOne = i;
simulations++;
console.log('testing combination '
+ rateLevelOne + ' ' + historyLevelOne + ' ' + breakStepOne + ' '
+ rateLevelTwo + ' ' + historyLevelTwo + ' ' + breakStepTwo + ' '
+ rateLevelThree + ' ' + historyLevelThree + ' ' + breakStepThree
);
console.log('performing test no ' + simulations);
}
}
}
}
}
}
}
}
}
Implementation of worker threads to the best of my ability.
const {
Worker, isMainThread, parentPort, workerData
} = require('worker_threads');
const os = require('os');
if (isMainThread) {
const startTime = Date.now();
const workers = [];
// const numberOfThreads = 1;
const numberOfThreads = os.cpus().length;
let completed = 0;
let minBreakStep = 10;
let maxBreakStep = 20;
let minMaxElements = [];
for (let i = minBreakStep; i <= maxBreakStep; i++) {
minMaxElements.push(i);
}
const numberOfElements = minMaxElements.length;
const numElementsPerThread = Math.ceil(numberOfElements / numberOfThreads);
let workerIndex = 0;
let allSimulations = 0;
for (let i = minBreakStep; i <= maxBreakStep; i += numElementsPerThread) {
let workerStart = i;
let workerEnd = i + numElementsPerThread - 1;
if (workerEnd > maxBreakStep) {
workerEnd = maxBreakStep
}
const worker = new Worker(__filename, {
workerData: {
workerIndex,
workerStart,
workerEnd,
}
});
worker.on('message', (message) => {
if (message.completed) {
completed++;
console.log('worker ' + message.workerIndex + ' completed ' + message.simulations + ' simulations.');
allSimulations += message.simulations;
}
if (completed === workers.length) {
console.log('Completed all ' + allSimulations + ' done!');
const endTime = Date.now();
const elapsedTime = (endTime - startTime) / 1000;
console.log(elapsedTime + ' second(s) to complete');
}
});
workerIndex++;
workers.push(worker);
}
} else {
let workerIndex = workerData.workerIndex;
let workerStart = workerData.workerStart;
let workerEnd = workerData.workerEnd;
let simulations = 0;
for (let i = workerStart; i <= workerEnd; i++) {
breakStepThree = i;
for (let i = 8; i <= 12; i++) {
historyLevelThree = i;
for (let i = 0; i <= 60; i += 5) {
rateLevelThree = i;
for (let i = 10; i <= 16; i++) {
breakStepTwo = i;
for (let i = 6; i <= 10; i++) {
historyLevelTwo = i;
for (let i = 0; i <= 50; i += 5) {
rateLevelTwo = i;
for (let i = 10; i <= 14; i++) {
breakStepOne = i;
for (let i = 4; i <= 8; i++) {
historyLevelOne = i;
for (let i = 0; i <= 40; i += 5) {
rateLevelOne = i;
simulations++;
// console.log('testing combination '
// + rateLevelOne + ' ' + historyLevelOne + ' ' + breakStepOne + ' '
// + rateLevelTwo + ' ' + historyLevelTwo + ' ' + breakStepTwo + ' '
// + rateLevelThree + ' ' + historyLevelThree + ' ' + breakStepThree
// );
// console.log('performing test no ' + simulations);
}
}
}
}
}
}
}
}
}
console.log('testing completed');
parentPort.postMessage({
completed: true,
workerIndex: workerIndex,
simulations: simulations,
});
}

Implementation of worker threads to the best of my ability.
const {
Worker, isMainThread, parentPort, workerData
} = require('worker_threads');
const os = require('os');
if (isMainThread) {
const startTime = Date.now();
const workers = [];
// const numberOfThreads = 1;
const numberOfThreads = os.cpus().length;
let completed = 0;
let minBreakStep = 10;
let maxBreakStep = 20;
let minMaxElements = [];
for (let i = minBreakStep; i <= maxBreakStep; i++) {
minMaxElements.push(i);
}
const numberOfElements = minMaxElements.length;
const numElementsPerThread = Math.ceil(numberOfElements / numberOfThreads);
let workerIndex = 0;
let allSimulations = 0;
for (let i = minBreakStep; i <= maxBreakStep; i += numElementsPerThread) {
let workerStart = i;
let workerEnd = i + numElementsPerThread - 1;
if (workerEnd > maxBreakStep) {
workerEnd = maxBreakStep
}
const worker = new Worker(__filename, {
workerData: {
workerIndex,
workerStart,
workerEnd,
}
});
worker.on('message', (message) => {
if (message.completed) {
completed++;
console.log('worker ' + message.workerIndex + ' completed ' + message.simulations + ' simulations.');
allSimulations += message.simulations;
}
if (completed === workers.length) {
console.log('Completed all ' + allSimulations + ' done!');
const endTime = Date.now();
const elapsedTime = (endTime - startTime) / 1000;
console.log(elapsedTime + ' second(s) to complete');
}
});
workerIndex++;
workers.push(worker);
}
} else {
let workerIndex = workerData.workerIndex;
let workerStart = workerData.workerStart;
let workerEnd = workerData.workerEnd;
let simulations = 0;
for (let i = workerStart; i <= workerEnd; i++) {
breakStepThree = i;
for (let i = 8; i <= 12; i++) {
historyLevelThree = i;
for (let i = 0; i <= 60; i += 5) {
rateLevelThree = i;
for (let i = 10; i <= 16; i++) {
breakStepTwo = i;
for (let i = 6; i <= 10; i++) {
historyLevelTwo = i;
for (let i = 0; i <= 50; i += 5) {
rateLevelTwo = i;
for (let i = 10; i <= 14; i++) {
breakStepOne = i;
for (let i = 4; i <= 8; i++) {
historyLevelOne = i;
for (let i = 0; i <= 40; i += 5) {
rateLevelOne = i;
simulations++;
// console.log('testing combination '
// + rateLevelOne + ' ' + historyLevelOne + ' ' + breakStepOne + ' '
// + rateLevelTwo + ' ' + historyLevelTwo + ' ' + breakStepTwo + ' '
// + rateLevelThree + ' ' + historyLevelThree + ' ' + breakStepThree
// );
// console.log('performing test no ' + simulations);
}
}
}
}
}
}
}
}
}
console.log('testing completed');
parentPort.postMessage({
completed: true,
workerIndex: workerIndex,
simulations: simulations,
});
}

In Node.js, I'm unaware of any easy to use the GPU. Depending on the nature of the work being done to test each combination and the characteristics of your host system, you can use the built-in worker_threads and/or cluster modules to spread out the work. The worker_threads module creates threads within a process. The cluster module creates separate processes.

You can for example use CUDA bindings to perform calculations on GPU. Maybe in this case it would be better to interface a C program and import/export the experimental design and results. https://github.com/kashif/node-cuda / https://www.npmjs.com/package/cuda-node-js
Additionally I would get rid of all these nested loops with something like below. For performance sake maybe get rid of the slicing, and check the parameters as the few lines below are just to get the idea across.
class ExperimentGenerator{
let pointer = 0;
const initialParams = [0,0,0,0,0,0,0,0];
let params = [...initialParams]
const maxValue = [10,10,10,10,10,10,10,10]
nextExperiment = () =>{
if(params[pointer] >= maxValue[pointer]){
pointer++;
//Reset all other parameters
params = [initialParams.slice(0,pointer),params[pointer],initialParams.slice(pointer)];
}
params[pointer]++;
return params;
}
}

Related

how dinamically variable javascript

I am a javascript beginner, I have a multiple choice exam project where I want to get response data for each selected answer. I can do it by typing the code manually but I want to make the code efficient because the data can be more than 50 questions.
heres my best code .
var i;
for (i = 1; i <= <?= session()->get('participant')['jml_soal'] ?>; i++) {
window['radio' + i] = document.querySelectorAll("input[name='optionTrue" + i + "']");
window['rubahtombol' + i] = document.getElementById("buton" + i);
}
let findSe = () => {
let selected = document.querySelector("input[name='optionTrue1']:checked").value;
var soalId = document.getElementById("idSoal1").value;
var opsiPilih = document.getElementById("jawaban" + selected).textContent
document.getElementById("pilihan1").textContent = ". " + opsiPilih;
rubahtombol1.classList.remove("btn-secondary");
rubahtombol1.classList.add("btn-primary")
}
let findSe1 = () => {
let selected = document.querySelector("input[name='optionTrue2']:checked").value;
var soalId = document.getElementById("idSoal2").value;
var opsiPilih = document.getElementById("jawaban" + selected).textContent
document.getElementById("pilihan2").textContent = ". " + opsiPilih;
rubahtombol2.classList.remove("btn-secondary");
rubahtombol2.classList.add("btn-primary")
}
radio1.forEach(radioBtn => {
radioBtn.addEventListener("change", findSe1);
});
radio2.forEach(radioBtn1 => {
radioBtn1.addEventListener("change", findSe2);
});
findSe1();
findSe2();
i'm trying to do this but not working
var i;
for (i = 1; i <= <?= session()->get('participant')['jml_soal'] ?>; i++) {
window['radio' + i] = document.querySelectorAll("input[name='optionTrue" + i + "']");
window['rubahtombol' + i] = document.getElementById("buton" + i);
window['findSe' + i] = () => {
let selected = document.querySelector("input[name='optionTrue1']:checked").value;
var soalId = document.getElementById("idSoal1").value;
console.log(selected);
var opsiPilih = document.getElementById("jawaban" + selected).textContent
console.log("aku pilih:" + opsiPilih);
console.log("id saol:" + soalId);
document.getElementById("pilihan1").textContent = ". " + opsiPilih;
window['rubahtombol'+i.classList.remove("btn-secondary")];
window['rubahtombol'+i.classList.add("btn-primary")];
}
}
radio1.forEach(radioBtn => {
radioBtn.addEventListener("change", findSe1);
});
radio2.forEach(radioBtn1 => {
radioBtn1.addEventListener("change", findSe2);
});
findSe1();
findSe2();
what i imagine is, i want do that in one looping
Your second approach looks pretty close, but you need to make i local to the loop body. See JavaScript closure inside loops – simple practical example
But you can make it a little cleaner with OOP.
class Button {
contructor(i) {
this.index = i;
this.radio = document.querySelectorAll(`input[name='optionTrue${i}']`);
this.rumbahtombol = document.getElementById("buton" + i);
this.radio.addEventListener("change", this.findSe.bind(this));
}
findSe() {
let selected = document.querySelector(`input[name='optionTrue${this.index}']:checked`).value;
let soalId = document.getElementById(`idSoal${this.index}`).value;
let opsiPilih = document.getElementById("jawaban" + selected).textContent;
document.getElementById(`pilihan${this.index}`).textContent = ". " + opsiPilih;
this.rubahtombol.classList.remove("btn-secondary");
this.rubahtombol.classList.add("btn-primary")
}
}
for (let i = 1; i <= <?= session()->get('participant')['jml_soal'] ?>; i++) {
new Button(i);
}
i did a little change from the code made by #Barmar and it worked
class Button {
contructor(i) {
let radio = [];
this.index = i;
radio[i] = document.querySelectorAll(`input[name='optionTrue` + i + `']`);
radio[i].forEach(radioBtn => {
radioBtn.addEventListener("change", this.findSe.bind(this));
});
}
findSe() {
let rubahtombol = []
let selected = document.querySelector(`input[name='optionTrue${this.index}']:checked`).value;
let soalId = document.getElementById(`idSoal${this.index}`).value;
let opsiPilih = document.getElementById("jawaban" + selected).textContent;
document.getElementById(`pilihan${this.index}`).textContent = ". " + opsiPilih;
rubahtombol = document.getElementById(`buton${this.index}`);
rubahtombol.classList.remove("btn-secondary");
rubahtombol.classList.add("btn-primary")
}
}
for (let i = 1; i <= <?= session()->get('participant')['jml_soal'] ?>; i++) {
new Button(i).contructor(i);
}

How to iterate a JavaScript code for two objects

I would like to apply same piece of code to two objects in JavaScript.
When calling getElementsByClass ,there appears 2 objects in my website.So I would like to apply the same code for both of them.Currently I'm applying it to only one Object (text[0]) and I would like to implement it also to text[1] .
var text=document.getElementsByClassName("th");
var text =text[0];
var newDom = '';
var animationDelay = 6;
for(let i = 0; i < text.innerText.length; i++)
{
newDom += '<span class="char">' + (text.innerText[i] == ' ' ? ' ' : text.innerText[i])+ '</span>';
}
text.innerHTML = newDom;
var length = text.children.length;
for(let i = 0; i < length; i++)
{
text.children[i].style['animation-delay'] = animationDelay * i + 'ms';
}
}
I think you want to do the same thing with using item[0] and item[1] together.
You can create a function. Or call this function by iterating your items too.
var text=document.getElementsByClassName("th");
function myFunc(text) {
var newDom = '';
var animationDelay = 6;
for(let i = 0; i < text.innerText.length; i++)
{
newDom += '<span class="char">' + (text.innerText[i] == ' ' ? ' ' : text.innerText[i])+ '</span>';
}
text.innerHTML = newDom;
var length = text.children.length;
for(let i = 0; i < length; i++)
{
text.children[i].style['animation-delay'] = animationDelay * i + 'ms';
}
}
}
myFunc(text[0]); // call functions with your items.
myFunc(text[1]);

Thumbnail not show on related post blogger [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I use blogger costum domain. Related post image thumbnail not show on the detail post (example this post). Image was upload (cache) on my subdomain.
this script on related post
<script>
//<![CDATA[
var related_blogUrl = "https://www.perantiguru.com";
var related_total = 6;
var related_thumbnail = 1;
var related_imgWidth = 210;
var related_imgHeight = 130;
(function(){
var relatedNum = 0; var relatedUrl = new Array(); var relatedImage = new Array(); var relatedTitle = new Array(); var relatedTotal = related_total; var callback = "relatedposts"; var containerID = document.getElementById("relatedposts"); var noImg = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAA3NCSVQICAjb4U/gAAAADElEQVQImWOor68HAAL+AX7vOF2TAAAAAElFTkSuQmCC"; var imgSize = [related_imgWidth, related_imgHeight]; window[callback] = function(data){ for (var i = 0; i < data.feed.entry.length; i++){ var entry = data.feed.entry[i]; relatedTitle[relatedNum] = entry.title.$t; for (var j = 0; j < entry.link.length; j++){ if ("alternate" == entry.link[j].rel){ relatedUrl[relatedNum] = entry.link[j].href; break; } } relatedImage[relatedNum] = noImg.replace("/s72-c/", "/w" + imgSize[0] + "-h" + imgSize[1] + "-p-k-no-nu/"); if ("media$thumbnail" in entry) { relatedImage[relatedNum] = entry.media$thumbnail.url.replace("/s72-c/", "/w"+imgSize[0]+"-h"+imgSize[1]+"-p-k-no-nu/"); } relatedNum++; } }; function filterTags(g, h) { var e = g.split("<"); for (var f = 0; f < e.length; f++) { if (e[f].indexOf(">") != -1) { e[f] = e[f].substring(e[f].indexOf(">") + 1, e[f].length) } } e = e.join(""); e = e.substring(0, h - 1); return e; }; function contains(a, e) { for (var f = 0; f < a.length; f++) { if (a[f] == e) return true; } return false; }; function removeDuplicates() { var v = new Array(0); var A = new Array(0); var w = new Array(0); for (var u = 0; u < relatedUrl.length; u++) { if (!contains(v, relatedUrl[u])) { v.length += 1; v[v.length - 1] = relatedUrl[u]; A.length += 1; A[A.length - 1] = relatedImage[u]; w.length += 1; w[w.length - 1] = relatedTitle[u]; } } relatedUrl = v; relatedImage = A; relatedTitle = w; }; function createRelated() { removeDuplicates(); for (var u = 0; u < relatedTitle.length; u++) { var B = Math.floor((relatedTitle.length - 1) * Math.random()); var s = relatedUrl[u]; var C = relatedImage[u]; var i = relatedTitle[u]; relatedUrl[u] = relatedUrl[B]; relatedImage[u] = relatedImage[B]; relatedTitle[u] = relatedTitle[B]; relatedUrl[B] = s; relatedImage[B] = C; relatedTitle[B] = i; } var r = 0; var D = Math.floor((relatedTitle.length - 1) * Math.random()); var z = D; var t = document.URL; var e = ""; while (r < relatedTotal) { if (relatedUrl[D] != t) { e += "<li>"; if (related_thumbnail >= 1) { e += "<div class='thumbnail'>"; e += "<a href='" + relatedUrl[D] + "' title='" + relatedTitle[D] + "'>"; e += "<img src='" + relatedImage[D] + "' alt='" + relatedTitle[D] + "' width='" + imgSize[0] +"' height='" + imgSize[1] + "'/>"; e += "</a>"; e += "</div>"; } e += "<div class='title'>"; e += "<a href='" + relatedUrl[D] + "' title='" + relatedTitle[D] + "'>" + relatedTitle[D] + "</a>"; e += "</div>"; e += "</li>"; r++; if (r == relatedTotal) { break; } } if (D < relatedTitle.length - 1) { D++; } else { D = 0; } if (D == z) { break; } } containerID.innerHTML = e; }; var labels = ""; var ralatedlist = document.querySelectorAll("span.list-item"); ralatedlist.forEach(function(list) { labels += 'label:"' + list.dataset.label + '"|'; }); var js = document.createElement("script"); var blogUrl = related_blogUrl.replace(/\/$/, ""); js.src = blogUrl + "/feeds/posts/summary?v=2&q=" + labels + "&alt=json&callback=" + callback + "&max-results=20"; js.onload = createRelated; document.getElementsByTagName("head")[0].appendChild(js);
})();
//]]>
</script>
help me to fix it
fixed, Thumbnail not show on related post blogger from external source
Before:
<b:if cond='data:blog.pageType == "item"'>
<div class='relatedposts'>
<h4>Post Lainnya</h4>
<ul id='relatedposts'>
<b:loop values='data:post.labels' var='label'>
<span class='list-item' expr:data-label='data:label.name'/>
</b:loop>
</ul>
</div>
</b:if>
<script>
//<![CDATA[
var related_blogUrl = "https://www.perantiguru.com";
var related_total = 6;
var related_thumbnail = 1;
var related_imgWidth = 210;
var related_imgHeight = 130;
(function(){
var relatedNum = 0; var relatedUrl = new Array(); var relatedImage = new Array(); var relatedTitle = new Array(); var relatedTotal = related_total; var callback = "relatedposts"; var containerID = document.getElementById("relatedposts"); var noImg = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAA3NCSVQICAjb4U/gAAAADElEQVQImWOor68HAAL+AX7vOF2TAAAAAElFTkSuQmCC"; var imgSize = [related_imgWidth, related_imgHeight]; window[callback] = function(data){ for (var i = 0; i < data.feed.entry.length; i++){ var entry = data.feed.entry[i]; relatedTitle[relatedNum] = entry.title.$t; for (var j = 0; j < entry.link.length; j++){ if ("alternate" == entry.link[j].rel){ relatedUrl[relatedNum] = entry.link[j].href; break; } } relatedImage[relatedNum] = noImg.replace("/s72-c/", "/w" + imgSize[0] + "-h" + imgSize[1] + "-p-k-no-nu/"); if ("media$thumbnail" in entry) { relatedImage[relatedNum] = entry.media$thumbnail.url.replace("/s72-c/", "/w"+imgSize[0]+"-h"+imgSize[1]+"-p-k-no-nu/"); } relatedNum++; } }; function filterTags(g, h) { var e = g.split("<"); for (var f = 0; f < e.length; f++) { if (e[f].indexOf(">") != -1) { e[f] = e[f].substring(e[f].indexOf(">") + 1, e[f].length) } } e = e.join(""); e = e.substring(0, h - 1); return e; }; function contains(a, e) { for (var f = 0; f < a.length; f++) { if (a[f] == e) return true; } return false; }; function removeDuplicates() { var v = new Array(0); var A = new Array(0); var w = new Array(0); for (var u = 0; u < relatedUrl.length; u++) { if (!contains(v, relatedUrl[u])) { v.length += 1; v[v.length - 1] = relatedUrl[u]; A.length += 1; A[A.length - 1] = relatedImage[u]; w.length += 1; w[w.length - 1] = relatedTitle[u]; } } relatedUrl = v; relatedImage = A; relatedTitle = w; }; function createRelated() { removeDuplicates(); for (var u = 0; u < relatedTitle.length; u++) { var B = Math.floor((relatedTitle.length - 1) * Math.random()); var s = relatedUrl[u]; var C = relatedImage[u]; var i = relatedTitle[u]; relatedUrl[u] = relatedUrl[B]; relatedImage[u] = relatedImage[B]; relatedTitle[u] = relatedTitle[B]; relatedUrl[B] = s; relatedImage[B] = C; relatedTitle[B] = i; } var r = 0; var D = Math.floor((relatedTitle.length - 1) * Math.random()); var z = D; var t = document.URL; var e = ""; while (r < relatedTotal) { if (relatedUrl[D] != t) { e += "<li>"; if (related_thumbnail >= 1) { e += "<div class='thumbnail'>"; e += "<a href='" + relatedUrl[D] + "' title='" + relatedTitle[D] + "'>"; e += "<img src='" + relatedImage[D] + "' alt='" + relatedTitle[D] + "' width='" + imgSize[0] +"' height='" + imgSize[1] + "'/>"; e += "</a>"; e += "</div>"; } e += "<div class='title'>"; e += "<a href='" + relatedUrl[D] + "' title='" + relatedTitle[D] + "'>" + relatedTitle[D] + "</a>"; e += "</div>"; e += "</li>"; r++; if (r == relatedTotal) { break; } } if (D < relatedTitle.length - 1) { D++; } else { D = 0; } if (D == z) { break; } } containerID.innerHTML = e; }; var labels = ""; var ralatedlist = document.querySelectorAll("span.list-item"); ralatedlist.forEach(function(list) { labels += 'label:"' + list.dataset.label + '"|'; }); var js = document.createElement("script"); var blogUrl = related_blogUrl.replace(/\/$/, ""); js.src = blogUrl + "/feeds/posts/summary?v=2&q=" + labels + "&alt=json&callback=" + callback + "&max-results=20"; js.onload = createRelated; document.getElementsByTagName("head")[0].appendChild(js);
})();
//]]>
</script>
After:
<b:if cond='data:blog.pageType == "item"'>
<div id='related-posts'>
<b:loop index='labelcount' values='data:post.labels' var='label'>
<script>
var currentURL = '<data:blog.url/>';
</script>
<b:if cond='data:labelcount < 1'>
<script async='async' expr:src='"/feeds/posts/default/-/" + data:label.name + "?alt=json-in-script&callback=display_related_posts"' type='text/javascript'/></b:if></b:loop>
</div><div style='clear:both'/>
</b:if>
<script type='text/javascript'>
/*<![CDATA[*/
var post_thumbnail_width = 180;
var post_thumbnail_height = 120;
var max_related_entries = 6;
function escapeRegExp(string){return string.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function replaceAll(str,term,replacement){return str.replace(new RegExp(escapeRegExp(term),"g"),replacement)}function display_related_posts(json_feed){for(var defaultnoimage="https://i.ibb.co/yS6JvBh/no-image.jpg",post_titles=new Array,title_num=0,post_urls=new Array,post_thumbnail_url=new Array,relatedpoststitle=(window.location.href,"Post Lainnya"),border_color="#DDDDDD",i=0;i<json_feed.feed.entry.length;i++){var feed_entry=json_feed.feed.entry[i];post_titles[title_num]=feed_entry.title.$t;try{post_thumbnail_url[title_num]=feed_entry.media$thumbnail.url}catch(error){s=feed_entry.content.$t,a=s.indexOf("<img"),b=s.indexOf('src="',a),c=s.indexOf('"',b+5),d=s.substr(b+5,c-b-5),-1!=a&&-1!=b&&-1!=c&&""!=d?post_thumbnail_url[title_num]=d:"undefined"!=typeof defaultnoimage?post_thumbnail_url[title_num]=defaultnoimage:post_thumbnail_url[title_num]="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAA3NCSVQICAjb4U/gAAAADElEQVQImWOor68HAAL+AX7vOF2TAAAAAElFTkSuQmCC"}for(var k=0;k<feed_entry.link.length;k++)"alternate"==feed_entry.link[k].rel&&(post_urls[title_num]=feed_entry.link[k].href,title_num++)}var random_entry=Math.floor((post_titles.length-1)*Math.random()),iteration=0;if(post_titles.length>0){var rp_heading=document.createElement("h2"),textnode=document.createTextNode(relatedpoststitle);rp_heading.appendChild(textnode),document.getElementById("related-posts").appendChild(rp_heading);var rp_container=document.createElement("div");rp_container.setAttribute("style","clear: both;"),rp_container.setAttribute("id","rp-container"),document.getElementById("related-posts").appendChild(rp_container)}for(;iteration<post_titles.length&&20>iteration&&max_related_entries>iteration;)if(post_urls[random_entry]!=currentURL){var rp_anchor=document.createElement("a");0!=iteration?rp_anchor.setAttribute("style","text-decoration:none;padding:10px;float:left;border-left: none "+border_color+";"):rp_anchor.setAttribute("style","text-decoration:none;padding:10px;float:left;"),rp_anchor.setAttribute("id","rp-anchor-"+iteration),rp_anchor.setAttribute("href",post_urls[random_entry]),document.getElementById("rp-container").appendChild(rp_anchor);var rp_img=document.createElement("img");rp_img.setAttribute("style","width:"+post_thumbnail_width+"px;height:"+post_thumbnail_height+"px; border:1px solid #CCCCCC;"),rp_img.setAttribute("id","rp-img-"+iteration);var pin=String(post_thumbnail_url[random_entry].match(/\/s72-c\//));post_thumbnail_url[random_entry]=replaceAll(post_thumbnail_url[random_entry],pin,"/w"+post_thumbnail_width+"-h"+post_thumbnail_height+"-p/"),rp_img.setAttribute("src",post_thumbnail_url[random_entry]),rp_img.setAttribute("alt","Matched post excerpt thumbnail in the post footer."),document.getElementById("rp-anchor-"+iteration).appendChild(rp_img);var rp_para=document.createElement("div");rp_para.setAttribute("style","width:"+post_thumbnail_width+"px; height:"+post_thumbnail_height+"px;border: 0pt none ; margin: auto; padding-top: 18px; line-height:1.6;"),rp_para.setAttribute("id","rp-para-"+iteration);var textnode=document.createTextNode(post_titles[random_entry]);rp_para.appendChild(textnode),document.getElementById("rp-anchor-"+iteration).appendChild(rp_para),iteration++,random_entry<post_titles.length-1?random_entry++:random_entry=0}else iteration++,random_entry<post_titles.length-1?random_entry++:random_entry=0;post_urls.splice(0,post_urls.length),post_thumbnail_url.splice(0,post_thumbnail_url.length),post_titles.splice(0,post_titles.length)}
/*]]>*/
</script>

array undefined in JavaScript

I've a array which is the following;
var imgArray = (function() {
var kleuren = ["harten", "klaveren", "koeken", "schoppen"];
var result = [];
for(var k = 0; k != kleuren.length; k++) {
for(var n = 1; n <= 13; ++n) {
result.push("images/" + kleuren[k] + "/" + kleuren[k] + n.toString() + ".png");
}
}
})();
And this is where I call my function/Array:
if(counter <= 5) {
var arrayIndex = computeIndex(type, face);
$('#cardplace' + counter).css("background-image", "url('" + imgArray[arrayIndex] + "')");
++counter;
} else {
alert("Je hebt te veel kaarten genomen...");
document.reload();
}
But my Nightly give the Error that imgArray is undefined,
where did i go wrong?
You need to
return result;
at the end of your function.

Javascript Hanging UI on IE6/7

Could anyone suggest performance improvements for the function I've written (below, javascript with bits of jquery)? Or point out any glaring, basic flaws? Essentially I have a javascript Google map and a set of list based results too, and the function is fired by a checkbox click, which looks at the selection of checkboxes (each identifying a 'filter') and whittles the array data down accordingly, altering the DOM and updating the Google map markers according to that. There's a 'fake' loader image in there too at the mo that's just on a delay so that it animates before the UI hangs!
function updateFilters(currentCheck) {
if (currentCheck == undefined || (currentCheck != undefined && currentCheck.disabled == false)) {
var delay = 0;
if(document.getElementById('loader').style.display == 'none') {
$('#loader').css('display', 'block');
delay = 750;
}
$('#loader').delay(delay).hide(0, function(){
if (markers.length > 0) {
clearMarkers();
}
var filters = document.aspnetForm.filters;
var markerDataArray = [];
var filterCount = 0;
var currentfilters = '';
var infoWindow = new google.maps.InfoWindow({});
for (i = 0; i < filters.length; i++) {
var currentFilter = filters[i];
if (currentFilter.checked == true) {
var filtername;
if (currentFilter.parentNode.getElementsByTagName('a')[0].textContent != undefined) {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].textContent;
} else {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].innerText;
}
currentfilters += '<li>' + $.trim(filtername) +
$.trim(document.getElementById('remhide').innerHTML).replace('#"','#" onclick="toggleCheck(\'' + currentFilter.id + '\');return false;"');
var nextFilterArray = [];
filterCount++;
for (k = 0; k < filterinfo.length; k++) {
var filtertype = filterinfo[k][0];
if (filterinfo[k][0] == currentFilter.id) {
var sitearray = filterinfo[k][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
if (filterCount > 1) {
nextFilterArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
} else {
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
if (filterCount > 1) {
var itemsToRemove = [];
for (j = 0; j < markerDataArray.length; j++) {
var exists = false;
for (k = 0; k < nextFilterArray.length; k++) {
if (markerDataArray[j] == nextFilterArray[k]) {
exists = true;
}
}
if (exists == false) {
itemsToRemove.push(j);
}
}
var itemsRemoved = 0;
for (j = 0; j < itemsToRemove.length; j++) {
markerDataArray.splice(itemsToRemove[j]-itemsRemoved,1);
itemsRemoved++;
}
}
}
}
if (currentfilters != '') {
document.getElementById('appliedfilters').innerHTML = currentfilters;
document.getElementById('currentfilters').style.display = 'block';
} else {
document.getElementById('currentfilters').style.display = 'none';
}
if (filterCount < 1) {
for (j = 0; j < filterinfo.length; j++) {
var filtertype = filterinfo[j][0];
if (filterinfo[j][0] == 'allvalidsites') {
var sitearray = filterinfo[j][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
var infoWindow = new google.maps.InfoWindow({});
var resultHTML = '<div id="page1" class="page"><ul>';
var count = 0;
var page = 1;
var paging = '<li class="selected">1</li>';
for (i = 0; i < markerDataArray.length; i++) {
var markerInfArray = markerDataArray[i].split('|');
var url = '';
var name = '';
var placename = '';
var region = '';
var summaryimage = 'images/controls/placeholder.gif';
var summary = '';
var flag = 'images/controls/placeholderf.gif';
for (j = 0; j < tsiteinfo.length; j++) {
var thissite = tsiteinfo[j].split('|');
if (thissite[0] == markerInfArray[2]) {
name = thissite[1];
placename = thissite[2];
region = thissite[3];
if (thissite[4] != '') {
summaryimage = thissite[4];
}
summary = thissite[5];
if (thissite[6] != '') {
flag = thissite[6];
}
}
}
for (k = 0; k < sitemapperinfo.length; k++) {
var thissite = sitemapperinfo[k].split('|');
if (thissite[0] == markerInfArray[2]) {
url = thissite[1];
}
}
var markerLatLng = new google.maps.LatLng(markerInfArray[1].toString(), markerInfArray[0].toString());
var infoWindowContent = '<div class="infowindow">' + markerInfArray[2] + ': ';
var siteurl = approot + '/sites/' + url;
infoWindowContent += '<strong>' + name + '</strong>';
infoWindowContent += '<br /><br/><em>' + placename + ', ' + region + '</em></div>';
marker = new google.maps.Marker({
position: markerLatLng,
title: $("<div/>").html(name).text(),
shadow: shadow,
icon: image
});
addInfo(infoWindow, marker, infoWindowContent);
markers.push(marker);
count++;
if ((count > 20) && ((count % 20) == 1)) { // 20 per page
page++;
resultHTML += '</ul></div><div id="page' + page + '" class="page"><ul>';
paging += '<li>' + page + '</li>';
}
resultHTML += '<li><div class="namehead"><h2>' + name + ' <span>' + placename + ', ' + region + '</span></h2></div>' +
'<div class="codehead"><h2><img alt="' + region + '" src="' + approot +
'/' + flag + '" /> ' + markerInfArray[2] + '</h2></div>' +
'<div class="resultcontent"><img alt="' + name + '" src="' + approot +
'/' + summaryimage +'" />' + '<p>' + summary + '</p>' + document.getElementById('buttonhide').innerHTML.replace('#',siteurl) + '</div></li>';
}
$('#filteredmap .paging').each(function(){
$(this).html(paging);
});
document.getElementById('resultslist').innerHTML = resultHTML + '</ul></div>';
document.getElementById('count').innerHTML = count + ' ';
document.getElementById('page1').style.display = 'block';
for (t = 0; t < markers.length; t++) {
markers[t].setMap(filteredMap);
}
});
}
}
function clearMarkers() {
for (i = 0; i < markers.length; i++) {
markers[i].setMap(null);
markers[i] = null;
}
markers.length = 0;
}
However, I'm suffering from performance issues (UI hanging) specifically in IE6 and 7 when the number of results is high, but not in any other modern browsers, i.e. FF, Chrome, Safari etc. It is much worse when the Google map markers are being created and added (if I remove this portion it is still slugglish, but not to the same degree). Can you suggest where I'm going wrong with this?
Thanks in advance :) Please be gentle if you can, I don't do much javascript work and I'm pretty new to it and jquery!
This looks like a lot of work to do at the client no matter what.
Why don't you do this at the server instead, constructing all the HTML there, and just refresh the relevant sections with the results of an ajax query?

Categories

Resources