I have created a function that creates some ammount of random cards, but my Init function returns undefined when I call it like init(1). Why doesn't it work? It should be like:
1. I'm calling a function for example init(1)
2. Init creates and shuffles cards and appends them to the body
// INIT
{
function init(difficulty) {
switch (difficulty) {
case 1:
createCards(4);
break;
case 2:
createCards(12);
break;
case 0:
createCards(24);
}
}
//FLIP CARD
function createCards(ammount) {
const gameCards = []
for (let i = 0; i < ammount; i++) {
const gameCard = document.createElement("div");
gameCard.className = "card card--click";
const gameCardFront = document.createElement("div");
const gameCardBack = document.createElement("div");
gameCard.appendChild(gameCardFront);
gameCard.appendChild(gameCardBack);
gameCardFront.className = "card__front card--reversed";
gameCardBack.className = "card__back";
const img = new Image();
function randImg() {
const uniqueSrc = {}
const imgArray = ["ball", "car", "fork", "spoon", "sun"];
const gameArray = [];
for (let i = 0; i < ammount * 2 + 1; i++) {
const randomSrc = Math.floor(Math.random() * (imgArray.length));
if (!uniqueSrc[randomSrc]) {
uniqueSrc[randomSrc] = randomSrc;
img.src = "img/" + imgArray[randomSrc] + ".png";
img.alt = imgArray[randomSrc];
gameArray.push(img);
} else {
i--;
}
}
return gameArray;
}
randImg();
gameCardBack.appendChild(img);
gameCards.push(gameCard)
}
return gameCards;
}
const cards = document.querySelectorAll(".card.card--click");
//FETCHING ALL CARDS
for (let i = 0; i < cards.length; i++) {
const card = cards[i];
//ADDING FLIP EFFECT TO EACH CARD
flipCard(card);
};
//FLIP EFFECT FUNCTION
function flipCard(card) {
card.addEventListener("click", function() {
const list = this.classList;
list.contains("card--flip") === true ? list.remove("card--flip") : list.add("card--flip");
});
};
function randomizer(array) {
for (let i = 0; i < array.length; i++) {
const j = Math.floor(Math.random() * (i + 1));
const tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
return array;
}
}
1) The thing is that youre not appending your cards to body. So you may want to return the cards in the init function:
function init(difficulty) {
switch (difficulty) {
case 1:
return createCards(4);
break;
case 2:
return createCards(12);
break;
case 0:
return createCards(24);
}
}
Then you can append the Array returned by init to body:
init(0).forEach(function(card){
document.body.appendChild(card);
});
2)Also this:
randImg();
doesnt make sense as randImg returns an array, you may wanna catch it:
arr=randImg();
3) Also the randImg will not work, you need to put the
const img=new Image();
into the loop.
4) And
const cards = document.querySelectorAll(".card.card--click");
Will be an empty collection unless you run the snippet above before...
Related
I am doing create multiple worker threads, in my case, i am trying to create 2:
This is my code to create work thread
function createWorker(data1, data2) {
return new Promise((resolve) => {
let worker = new Worker();
worker.postMessage(data1, data2);
worker.onmessage = (event) => {
postMessageRes = event.data;
if (postMessageRes == 200) {
// loadCOPC();
} else {
workerCount += 1;
let position = postMessageRes[0];
let color = postMessageRes[1];
for (let i = 0; i < position.length; i++) {
positions.push(position[i]);
colors.push(colors[i]);
}
resolve(true);
}
};
});
}
and using it in my loop
for (let m = 0; m < keyCountMap.length; ) {
let remaining = totalNodes - doneCount;
let numbWorker = Math.min(chunk, remaining);
for (let i = 0; i < numbWorker; i++) {
promises.push(createWorker([keyCountMap[m], keyCountMap[m + 1]]));
m += 2;
}
Promise.all(promises).then((response) => {
console.log("one chunk finishes");
});
}
The code works fine if i instead of all these use one static work thread and call postMessage in the loop for only one but not while i am trying to make chunk like here in the code.
When i run the code, my browser freeze
This is my worker file:
import { Copc, Key } from "copc";
import * as THREE from "three";
const color = new THREE.Color();
const colors = [];
let firstTime = true;
var nodePages, pages, receivedData, copc;
let x_min, y_min, z_min, x_max, y_max, z_max, width;
let positions = [];
let filename = "https://s3.amazonaws.com/data.entwine.io/millsite.copc.laz";
const readPoints = (id, getters) => {
let returnPoint = getXyzi(id, getters);
positions.push(
returnPoint[0] - x_min - 0.5 * width,
returnPoint[1] - y_min - 0.5 * width,
returnPoint[2] - z_min - 0.5 * width
);
const vx = (returnPoint[3] / 65535) * 255;
color.setRGB(vx, vx, vx);
colors.push(color.r, color.g, color.b);
firstTime = false;
};
function getXyzi(index, getters) {
return getters.map((get) => get(index));
}
async function load() {
copc = await Copc.create(filename);
let scale = copc.header.scale[0];
[x_min, y_min, z_min, x_max, y_max, z_max] = copc.info.cube;
width = Math.abs(x_max - x_min);
// let center_x = (x_min + x_max) / 2;
// let center_y = (y_min + y_max) / 2;
// let center_z = (z_min + z_max) / 2;
receivedData = await Copc.loadHierarchyPage(
filename,
copc.info.rootHierarchyPage
);
nodePages = receivedData.nodes;
pages = receivedData.pages;
postMessage(200);
}
async function loadData(myRoot, pointCount) {
const view = await Copc.loadPointDataView(filename, copc, myRoot);
let getters = ["X", "Y", "Z", "Intensity"].map(view.getter);
for (let j = 0; j < pointCount; j += 1) {
readPoints(j, getters);
}
postMessage([positions, colors]);
}
load();
onmessage = function (message) {
let mapIndex = message.data[0];
let pointCount = message.data[1];
console.log(mapIndex);
let myRoot = nodePages[mapIndex];
loadData(myRoot, pointCount);
};
The issue might be due to creating multiple worker threads in a loop, which could lead to a large number of worker threads and result in high memory usage and ultimately lead to freezing of the browser.
One approach to resolve this issue is to limit the number of worker threads created at a time by setting a maximum number of workers, and creating new workers only when some workers have completed their tasks.
Here's an example of the code that implements this approach:
const MAX_WORKERS = 4;
let promises = [];
let workerCount = 0;
function createWorker(data1, data2) {
return new Promise((resolve) => {
let worker = new Worker();
worker.postMessage(data1, data2);
worker.onmessage = (event) => {
postMessageRes = event.data;
if (postMessageRes == 200) {
// loadCOPC();
} else {
workerCount += 1;
let position = postMessageRes[0];
let color = postMessageRes[1];
for (let i = 0; i < position.length; i++) {
positions.push(position[i]);
colors.push(colors[i]);
}
if (workerCount === MAX_WORKERS) {
workerCount = 0;
promises = [];
}
resolve(true);
}
};
});
}
for (let m = 0; m < keyCountMap.length; ) {
let remaining = totalNodes - doneCount;
let numbWorker = Math.min(chunk, remaining);
for (let i = 0; i < numbWorker; i++) {
promises.push(createWorker([keyCountMap[m], keyCountMap[m + 1]]));
m += 2;
}
if (workerCount === MAX_WORKERS) {
Promise.all(promises).then((response) => {
console.log("one chunk finishes");
});
}
}
I created a slider-puzzle game and recently decided to reafctor the code using OOP. Besides I added a new functionality, so a player can change the size of the game board (3X3, 4X4, 5X5 etc.) by pressing a sertain button. But somehow a shuffle function stopped working. If you have any ideas of what I might do wrong, I will be very grateful if you let me know.
"use strict";
///////////////////////////////////////////////////////////////////////////
// Elements
const body = document.body;
const root = document.querySelector(".root");
const buttons = document.createElement("div");
const table = document.querySelector(".table");
const timeAndMoves = document.createElement("div");
const cubeSize = 125;
let cubes = [];
let gameRoundResults = {round: [], moves: [], time: []};
let countMoves = 0;
let gameRound = 0;
let cube, timer, left, top, tr, td;
let rowColumnLength = [3, 4, 5, 6, 7, 8]; // the default size of the game board - 4 columns and 4 rows
let boardSize = [9, 16, 15, 36, 49, 64];
let cubesArray = [];
let blankSpace = document.querySelector(".blank_space");
blankSpace = {
// blank space coords
};
// calculating coordinates of each cube and setting style
function getCoords(a, b) {
return Math.abs(a - b);
}
function setElementStyle(a, b) {
return `${a * b}px`;
}
// changing position of cubes
function changePosition(i) {
let cube = cubes[i];
const blankSpaceLeft = blankSpace.left;
const blankSpaceTop = blankSpace.top;
let coordsLeft = getCoords(blankSpace.left, cube.left);
let coordsTop = getCoords(blankSpace.top, cube.top);
if (
(blankSpaceLeft === cube.left && blankSpaceTop === cube.top) ||
coordsLeft + coordsTop > 1
) {
return;
} else {
countMoves++;
calcMoves.textContent = `Moves: ${countMoves}`;
}
cube.element.style.left = setElementStyle(blankSpace.left, cubeSize);
cube.element.style.top = setElementStyle(blankSpace.top, cubeSize);
blankSpace.top = cube.top;
blankSpace.left = cube.left;
cube.top = blankSpaceTop;
cube.left = blankSpaceLeft;
const winCondition = cubes.every(
(cube) => cube.value - 1 === cube.top * rowColumnLength + cube.left
);
if (winCondition) {
winAnnouncement();
clearInterval(timer);
gameRound++;
gameRoundResults.round.push(gameRound);
gameRoundResults.moves.push(countMoves);
gameRoundResults.time.push(setTimer.textContent);
}
}
// resetting the game, so after clicking on a shuffle button the original game board won't overlay newly shuffled cubes
const resetGame = () => {
clearInterval(timer);
setTimer.textContent = `Time: 00:00`;
countMoves = 0;
calcMoves.textContent = `Moves: ${countMoves}`;
[...root.children].forEach((el) => {
root.removeChild(el); //removing elements from the board
});
[...table.children].forEach((el) => {
table.removeChild(el); //removing elements from the board
});
cubes.splice(0); // deleting all elements starting from index 0
blankSpace.top = 0; // resetting coordinates
blankSpace.left = 0;
};
// creating a timer
const setTimer = document.createElement("div");
setTimer.classList.add("timer");
setTimer.textContent = `Time: 00:00`;
body.append(setTimer);
function startTimer() {
let sec = 0;
let min = 0;
timer = setInterval(() => {
setTimer.textContent =
"Time: " + `${min}`.padStart(2, 0) + ":" + `${sec}`.padStart(2, 0);
sec++;
if (sec >= 60) {
sec = 0;
min++;
}
}, 1000);
}
// creating moves counter
const calcMoves = document.createElement("div");
calcMoves.classList.add("count_moves");
calcMoves.textContent = `Moves: ${countMoves}`;
body.append(calcMoves);
////////////////////////////////////////////////////////////////////////////////////
// Creating buttons using OOP and adding event listeners to each of them
class Button {
constructor(name, attribute, classList, textContent, value) {
this.name = document.createElement("button");
this.name.setAttribute("id", attribute);
this.name.classList.add(classList);
this.textContent = this.name.textContent = textContent;
buttons.append(this.name);
}
//Methods that will be added to .prototype property
addEventShuffle() {
this.name.addEventListener("click", function () {
shuffle(cubesArray);
});
}
addEventStop() {
this.name.addEventListener("click", function () {
clearInterval(timer);
});
}
addEventResult() {
this.name.addEventListener("click", function () {
clearInterval(timer);
tableCreate();
showResults();
});
}
clickOnlyOnce() {
this.name.addEventListener("click", function () {
this.disabled = "disabled";
});
}
clickOnlyOnceDisabled() {
this.name.removeAttribute("disabled");
}
renderCubesNumber(number){
this.name.addEventListener("click", function () {
cubesArray.push(...Array(boardSize[number]).keys());
setPosition(boardSize = boardSize[number], rowColumnLength = rowColumnLength[number]);
console.log(cubesArray);
});
}
}
const shuffleButton = new Button(
"shuffleButton",
"button",
"shuffleButton",
"SHUFFLE"
);
const stopButton = new Button("stopButton", "button", "stopButton", "STOP");
const saveButton = new Button("saveButton", "button", "saveButton", "SAVE");
const resultsButton = new Button( "resultsButton", "button", "resultsButton", "RESULT");
shuffleButton.addEventShuffle();
stopButton.addEventStop();
resultsButton.addEventResult();
resultsButton.clickOnlyOnce();
// Creating size buttons
for(let i = 3; i <= 8; i++){
new Button("rowsCols", "button", "row_col_length", `${i}X${i}`).renderCubesNumber(i - 3);
}
// implementing shuffle functionality
function shuffle(cubesArray) {
for (let i = cubesArray.length - 1; i > 0; i--) {
resetGame(); // deleting original game board
setPosition(cubesArray); // creating a new shuffled game board
startTimer();
let j = Math.floor(Math.random() * (i + 1));
[cubesArray[i], cubesArray[j]] = [cubesArray[j], cubesArray[i]];
// [cubesArray[i], cubesArray[newPos]] = [cubesArray[newPos], cubesArray[i]]; //swapping original and randomized coordinates
console.log(
([cubesArray[i], cubesArray[j]] = [cubesArray[j], cubesArray[i]])
);
}
}
////////////////////////////////////////////////////////////////////////////////////
// Creating banners using OOP
class Banner {
constructor(name, classList, textContent, bannerMessage, bannerMessageClass) {
this.name = document.createElement("div");
this.name.classList.add(classList);
this.bannerMessage = document.createElement("h2");
this.bannerMessage.classList.add(bannerMessageClass);
this.bannerMessage.textContent = textContent;
root.append(this.bannerMessage);
root.append(this.name);
}
removeBanner() {
this.name.addEventListener("click", () => {
resultBanner.classList.remove("result_banner");
resultsButton.clickOnlyOnceDisabled();
});
}
}
// const startBanner = new Banner("startBanner","start_banner", `Slider puzzle challenge Click on 'Shuffle' to start the game!`, "bannerMessage","banner_message"
// );
// create pop-up if the user wins
function winAnnouncement() {
const winMessage = new Banner(
"winAnnounce",
"win_announce",
`Congrats! You solved the puzzle! Moves: ${countMoves} | ${setTimer.textContent}`,
"winMessage",
"win_message"
);
}
// Creating a result banner
function showResults() {
const resultBanner = document.createElement("div");
resultBanner.classList.add("result_banner");
const closeBanner = document.createElement("div");
closeBanner.classList.add("close_banner");
root.append(resultBanner);
table.append(closeBanner);
tableCreate();
const resultMessage = document.createElement("h2");
resultMessage.classList.add("banner_message");
resultBanner.append(resultMessage);
closeBanner.addEventListener("click", () => {
resultBanner.classList.remove("result_banner");
resultsButton.clickOnlyOnceDisabled();
[...table.children].forEach((el) => {
table.removeChild(el); //removing elements from the board
});
});
}
function tableCreate() {
const tbl = document.createElement("table");
tbl.classList.add("score_table");
for (let i = 0; i < 11; i++) {
tr = tbl.insertRow();
td = tr.insertCell();
if (gameRound === i + 1) {
td.appendChild(
document.createTextNode(
`Round: ${i + 1} | Moves: ${gameRoundResults.moves[i]} | ${gameRoundResults.time[i]}`
)
);
} else {
td.appendChild(
document.createTextNode(`Round: ${i + 1} | Moves: 0 | Time: 00:00`)
);
}
td.style.border = "1px solid black";
}
table.appendChild(tbl);
}
buttons.classList.add("button");
body.append(buttons);
// creating cubes
function setPosition() {
for (let i = 0; i < boardSize; i++) {
cube = document.createElement("div");
cube.classList.add("cube");
const value = i + 1; // adding +1 to the cubes' values to start the order from 1 (123...) instead of 0 (0123...)
cube.textContent = value;
left = i % rowColumnLength; // setting horizontal position
cube.style.left = setElementStyle(cubeSize, left);
top = (i - left) / rowColumnLength; // setting vertical position
cube.style.top = setElementStyle(cubeSize, top);
root.append(cube);
if (value === boardSize) {
// separating basic cubes with a blank space which is going to be the 16th cube
cube.classList.add("blank_space"); // adding a class to the last cube, so it'll be possible to hide it using css
blankSpace.top = top;
blankSpace.left = left;
blankSpace.value = value;
blankSpace.element = cube;
cubes.push(blankSpace);
} else {
cubes.push({
top: top,
left: left,
value: value,
element: cube,
});
}
cube.addEventListener("click", () => {
changePosition(i);
});
}
}
setPosition();
To solve the problem I've tried to refactor the shuffle function, but nothing works. In the screenshot you can see the results of console.logs
I need to make a coin flip 20x and display the coin, and the results x times each. I am trying to use decrement to determine the coin flip. And then need to display the flip x number of times. I am running into an issue of how to write it using this. and decrement.
const coin = {
state: 0,
flip: function () {
this.state = Math.floor(Math.random() * 2) == 0 ? "tails" : "heads";
// 0 or 1: use "this.state" to access the "state" property on this object.
},
toString: function () {
if (this.state === 0) {
sides = "heads";
} else if (this.state === 1) {
sides = "tails";
}
return sides;
},
toHTML: function () {
const image = document.createElement("img");
let h1 = document.querySelector("h1");
h1.append(image);
if (this.state === 0) {
image.src = "images/tails.png";
} else if (this.state === 1) {
image.src = "image/heads.png";
}
return image;
},
};
function display20Flips() {
const results = [];
for (let i = 0; i < 20; i++) {
coin.flip();
h3.innerHTML += coin.state;
results.push(coin.state++);
}
You can also approach it functionally. This will help you focus on one problem at a time:
// Store the coin flip state as a boolean (true or false)
function randomBoolean () {
return Boolean(Math.floor(Math.random() * 2));
}
// Convert the boolean state to a "side" string
// heads is false, tails is true
function asCoinSide (bool) {
return bool ? 'tails' : 'heads';
}
function createCoinImage (bool) {
const side = asCoinSide(bool);
const image = document.createElement('img');
image.alt = side;
// StackOverflow doesn't have access to your local images,
// so this will show an error in the code snippet demo
// when the URL is loaded, but will work if the images exist:
image.src = `images/${side}.png`;
return image;
}
function displayCoinFlips (count = 20) {
const div = document.querySelector('div.coins');
const results = [];
for (let i = 0; i < count; i += 1) {
// Get a state
const state = randomBoolean();
results.push(state);
// Use the state to create the image
const image = createCoinImage(state);
// And append it to the container div
div.appendChild(image);
}
return results;
}
function displaySummary (states) {
const div = document.querySelector('div.summary');
let headsCount = 0;
let tailsCount = 0;
// Count the heads vs. tails results
// Remember: heads is false, tails is true
for (const state of states) {
if (state) tailsCount += 1;
else headsCount += 1;
}
div.textContent = `Heads: ${headsCount}, Tails: ${tailsCount}`;
}
const states = displayCoinFlips();
displaySummary(states);
<div class="coins"></div>
<div class="summary"></div>
You had some issues with your code. I fixed them. Still, the code needs to be a little redesigned to have a class Coin and then coin = new Coin().
const coin = {
state: 0,
flip: function() {
this.state = Math.floor(Math.random() * 2) == 0 ? "tails" : "heads";
},
toString: function() {
if (this.state === 0) {
sides = "heads";
} else if (this.state === 1) {
sides = "tails";
}
return sides;
},
toHTML: function() {
let h1 = document.querySelector(".container");
const div = document.createElement("div");
if (this.state === "tails") {
div.innerText = "images/tails.png";
} else {
div.innerText = "image/heads.png";
}
h1.append(div);
return div;
},
};
function displayFlips(n) {
const results = [];
for (let i = 0; i < n; i++) {
coin.flip();
coin.toHTML();
results.push(coin.state);
}
return results;
}
console.log(displayFlips(20));
<div class="container">
</div>
I wrote my code to search string for keywords and extracting needed data, but I have problems when I'm trying to search with keywords in arrays named: sort, title and artist. When I'm doing it I get an error about potential infinite loop.
var type = ['track','tracks','song','songs','album','albums'];
var artist = ['created by', 'made by'];
var genre = ['genre'];
var limit = ['set limit'];
var title = ['title','name'];
var sort = ['sort by', 'classificate by', 'separate by'];
var sortBy = ['popularity'];
// function changeWordsToNumbers(words) {
// if (msg.numbers[words])
// return msg.numbers[words];
// }
function searchForIndex(instruction, keywords) {
for (i = 0; i < keywords.length; i++) {
let search = instruction.search(keywords[i]);
if (search)
return search;
}
return false;
}
function getSearchResult(wanted) {
var searchResult = {
artist : searchForIndex(wanted, artist),
genre : searchForIndex(wanted, genre),
limit : searchForIndex(wanted, limit),
type : searchForIndex(wanted, type),
title : searchForIndex(wanted, title),
sort : searchForIndex(wanted, sort),
sortBy : searchForIndex(wanted, sortBy)
};
return searchResult;
}
function removeJunkKeyword(searchResult,instruction) {
for(var property in searchResult) {
if(searchResult.hasOwnProperty(property)) {
if(searchResult[property] != - 1) {
instruction = instruction.slice(0, searchResult[property] - 1);
}
}
}
return instruction;
}
function checkExist(searchResult) {
for(var property in searchResult) {
if(searchResult.hasOwnProperty(property)) {
if(searchResult[property] != -1)
return false;
}
}
return true;
}
function findAndCleanQuery(instruction, keywords) {
var exist = instruction.search(keywords);
var result = instruction.slice(exist + keywords.length + 1, instruction.length);
var searchResult = getSearchResult(result);
if (exist != -1) {
if (checkExist(searchResult)) {
return result;
} else {
result = removeJunkKeyword(searchResult,result);
return result;
}
}
return false;
}
function searchFor(instruction, keywords) {
for (i = 0; i < keywords.length; i++) {
let result = findAndCleanQuery(instruction,keywords[i]);
if (result)
return result;
}
return false;
}
function searchForType(instruction) {
for (i = 0; i < type.length; i++) {
let search = instruction.search(type[i])
if(search)
return type[i];
}
return false;
}
function searchForKeywords(instruction) {
msg.artist = searchFor(instruction, artist);
msg.type = searchForType(instruction, type);
msg.genre = searchFor(instruction, genre);
msg.limit = searchFor(instruction, limit);
msg.title = searchFor(instruction, title);
msg.sort = searchFor(instruction, sortreg);
}
var msg = {}
msg.instruction = 'Search for me';
searchForKeywords(msg.instruction);
console.log(msg.artist);
console.log(msg.type);
console.log(msg.genre);
console.log(msg.limit);
console.log(msg.title);
console.log(msg.sort);
Link for code: https://repl.it/J4Mc/9
PS. The object msg is used by node-red to communicate between nodes.
The issue is that you're doing this on several of your loops:
for (i = 0; i < keywords.length; i++) {
...where you should be doing this instead:
for (let i = 0; i < keywords.length; i++) {
Without using let, the variable i is effectively global. Each time you went into a new loop it got reset to 0, so it was never able to increase, which created the infinite loop.
As a side note, you'll also notice sortreg is undefined when it's used on line 98.
I have an array like below
var colorArray = ["#a", "#b", "#c", "#d", "#e"];
From this I will generate a map like this
function initilizeColorMap(){
for(var i = 0 ;i <colorArray.length ;i++){
colorTrackingMap[i] = {value: colorArray [i],state:"unused"};
}
}
Hopw i can iterate through the map when i need a color (next color from the map ) by checking the state in javascript..?
You can have a method that will return the next color. Check out this jsfiddle : http://jsfiddle.net/QYWDb/
var colorArray = ["#a", "#b", "#c", "#d", "#e"];
var colorTrackingMap = [];
var currentIndex = -1;
for(var i = 0 ;i <colorArray.length ;i++){
colorTrackingMap[i] = {value: colorArray [i],state:"unused"};
}
function getNextColor() {
if (currentIndex > colorTrackingMap.length)
currentIndex = 0;
else
currentIndex++;
while ( colorTrackingMap[currentIndex] !== undefined &&
colorTrackingMap[currentIndex].state !== "unused" ) {
currentIndex++;
}
if ( colorTrackingMap[currentIndex] )
return colorTrackingMap[currentIndex].value;
else
return "No color available";
}
If you need color according to given index you don't have to iterate, use such code:
var currentIndex = 0;
function Next() {
var tracking = colorTrackingMap[currentIndex];
alert("color: " + tracking.value + ", state: " + tracking.state);
currentIndex++;
if (currentIndex >= colorTrackingMap.length)
currentIndex = 0;
}
Live test case.
If you mean searching the array for item with specific value, just use ordinary loop:
function Find() {
var color = document.getElementById("color").value;
var state = "";
for (var i = 0; i < colorTrackingMap.length; i++) {
if (colorTrackingMap[i].value.toLowerCase() === color) {
state = colorTrackingMap[i].state;
break;
}
}
if (state.length == 0) {
alert("color isn't mapped");
} else {
alert("state: " + state);
}
}
You can also pass the color as function argument, this is just for sake of example.
Updated test case.
You could use something like this:
var ColourMap = function (arr) {
var _map = [],
out = [],
i,
len;
// Set up the colour map straight away
for (i = 0, len = arr.length; i < len; i++) {
_map.push({
value: arr[i],
state: "unused"
});
}
return {
get_next: function () {
var i,
len,
next;
for (i = 0, len = _map.length; i < len; i++) {
if (_map[i].state === "unused") {
next = _map[i];
break;
}
}
return next;
}
}
};
And then use something like:
var m = new ColourMap(["#a", "#b", "#c", "#d", "#e"]);
m.get_next(); // get the next available element
Here's a working example.