I am trying to draw a graph based on a calculator and the result of the equation is used as one of the axis in this case Y in order to make the first point and the second input file is for X axis but I can't manage to take the result into the next function. any recommendations or approach?
Here is the JS
function parseCalculationString(s) {
var calculation = [],
current = '';
for (var i = 0, ch; ch = s.charAt(i); i++) {
if ('^*/+-'.indexOf(ch) > -1) {
if (current == '' && ch == '-') {
current = '-';
} else {
calculation.push(parseFloat(current), ch);
current = '';
}
} else {
current += s.charAt(i);
}
}
if (current != '') {
calculation.push(parseFloat(current));
}
return calculation;
}
function removeBrackets(s) {
let regEx = /\((.*?)\)/g;
let ops = s.match(regEx);
for (var i = 0; i < ops.length; i++) {
let op = ops[i];
let res = calculate(parseCalculationString(op.replace('(', '').replace(')', '')));
s = s.replace(op, res);
}
return s;
}
function calculate(calc) {
var ops = [
{
'^': function(a, b) {
return Math.pow(a, b);
}
}, {
'*': function(a, b) {
return a * b
},
'/': function(a, b) {
return a / b
},
}, {
'+': function(a, b) {
return a + b
},
'-': function(a, b) {
return a - b
}
}],
newCalc = [],
currentOp;
for (var i = 0; i < ops.length; i++) {
for (var j = 0; j < calc.length; j++) {
if (ops[i][calc[j]]) {
currentOp = ops[i][calc[j]];
} else if (currentOp) {
newCalc[newCalc.length - 1] = currentOp(newCalc[newCalc.length - 1], calc[j]);
currentOp = null;
} else {
newCalc.push(calc[j]);
}
console.log(newCalc);
}
calc = newCalc;
newCalc = [];
}
if (calc.length > 1) {
console.log('Error: no funciona');
return calc;
} else {
return calc[0];
}
}
var calculateButton = document.getElementById('calculate'),
userInput = document.getElementById('userInput'),
sustuir = document.getElementById('userInputX'),
result = document.getElementById('result');
calculateButton.addEventListener('click', function() {
result.innerHTML = "la respuesta de Y " + calculate(
parseCalculationString(removeBrackets(
(userInput.value)
))
);
return calculateButton;
});
window.onload = function() {
var dps = []; //dataPoints.
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Result"
},
data: [{
type: "line",
dataPoints: dps
}]
});
function addDataPointsAndRender() {
xValue = Number(document.getElementById("result").value);
yValue = Number(document.getElementById("userInputX").value);
dps.push({
x: xValue,
y: yValue
});
chart.render();
}
var renderButton = document.getElementById("calculate");
renderButton.addEventListener("click", addDataPointsAndRender);
}
here is the HTMl
<div class="container">
<h1>Test Part 1 </h1>
<p>Example 2x*(2+2) use * in input before parentheses in order to work properly.</p>
<input type="text" id="userInput" />
<input type="text" id="userInputX" />
<input type="button" value="Calculate" id="calculate" />
<div id="result"></div>
<div id="chartContainer" style="height: 270px; width: 100%;"></div>
</div>
thanks in advance
Related
Over my head with javascript. I'm trying to get the cards to shuffle when clicking next.
Currently, it moves forward with one random shuffle and stops. Back and forward buttons then no longer work at that point.
Please help—many thanks.
When I'm lost and unsure what sample of the code to pinpoint, the captions go up to 499. The sample is also here: https://rrrhhhhhhhhh.github.io/sentences/
Very new to javascript. So any help is greatly appreciated. Very open to better ways to achieve this???
How I have it set up:
HTML:
var r = -1;
var mx = 499; // maximum
var a = new Array();
function AddNumsToDict(){
var m,n,i,j;
i = 0;
j = 0;
while (i <= 499)
{
m = (500 * Math.random()) + 1;
n = Math.floor(m);
for (j=0;j<=499;j++)
{
if (a[j] == (n-1))
{
j = -1;
break;
}
}
if (j != -1)
{
//a.push(n-1);
a[i] = (n-1);
i++;
j=0;
}
}
return;
}
function startup()
{
writit('SENTENCES<br><br><br>Robert Grenier', 'test');
SetCookie("pg", -1);
AddNumsToDict();
}
function SetCookie(sName, sValue)
{
document.cookie = sName + "=" + escape(sValue) + ";"
}
function GetCookie(sName)
{
// cookies are separated by semicolons
var aCookie = document.cookie.split("; ");
for (var i=0; i < aCookie.length; i++)
{
// a name/value pair (a crumb) is separated by an equal sign
var aCrumb = aCookie[i].split("=");
if (sName == aCrumb[0])
return unescape(aCrumb[1]);
}
// a cookie with the requested name does not exist
return null;
}
function doBack(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
//if ((oNxt) && (oPrev))
//{
var num = GetCookie("pg");
if (num == mx){ //maximum
SetCookie("pg",parseInt(num) - 1);
num = GetCookie("pg");
}
// oNxt.disabled = false;
// if (num <= 1){
// oPrev.disabled = true;
// }
if (num >= 1){
num--;
writit(Caption[a[num]], 'test');
SetCookie("pg",num);
}
//}
}
function doNext(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
// if ((oNxt) && (oPrev))
// {
var num = GetCookie("pg");
// if (num > -1){
// oPrev.disabled = false;
// }
// else{
// oPrev.disabled = true;
// }
// if (num >= parseInt(mx)-1){ //maximum - 1
// oNxt.disabled = true;
// }
// else {
// oNxt.disabled = false;
// }
if (num <= parseInt(mx)-2){
num++;
writit(Caption[a[num]],'test');
SetCookie("pg",num);
}
// }
}
function writit(text,id)
{
if (document.getElementById)
{
x = document.getElementById(id);
x.innerHTML = '';
x.innerHTML = text;
}
else if (document.all)
{
x = document.all[id];
x.innerHTML = text;
}
else if (document.layers)
{
x = document.layers[id];
l = (480-(getNumLines(text)*8))/2;
w = (764-(getWidestLine(text)*8))/2;
text2 = '<td id=rel align="center" CLASS="testclass" style="font:12px courier,courier new;padding-left:' + w.toString() + 'px' + ';padding-top:' + l.toString() + 'px' + '">' + text + '</td>';
x.document.open();
x.document.write(text2);
x.document.close();
}
}
function getNumLines(mystr)
{
var a = mystr.split("<br>")
return(a.length);
}
function getWidestLine(mystr)
{
if (mystr.indexOf(" ") != -1)
{
re = / */g;
mystr = mystr.replace(re,"Z");
//alert(mystr);
}
if (mystr.indexOf("<u>") != -1)
{
re = /<u>*/g;
mystr = mystr.replace(re, "");
re = /<\/u>*/g;
mystr = mystr.replace(re, "");
}
if (mystr.indexOf("<br>") != -1)
{
var ss, t;
var lngest;
ss = mystr.split("<br>");
lngest = ss[0].length;
for (t=0; t < ss.length; t++)
{
if (ss[t].length > lngest)
{
lngest = ss[t].length;
}
}
}
else {
lngest = mystr.length;
}
return(lngest);
}
// -->
</script>
<body bgcolor="gainsboro" onload="startup();">
<table bgcolor="white" border height="480px" width="764px" cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<table nowrap>
<tr>
<td><img width="700px" height="1px" src="./resources/images/w.gif"></td>
<td>
<div class="testclass" id="test"></div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<center>
<form>
<p>
<input type="button" onclick="doBack(); return false" value="Back">
<input type="button" onclick="doNext(); return false" value="Next">
JS:
var _____WB$wombat$assign$function_____ = function(name) {return (self._wb_wombat && self._wb_wombat.local_init && self._wb_wombat.local_init(name)) || self[name]; };
if (!self.__WB_pmw) { self.__WB_pmw = function(obj) { this.__WB_source = obj; return this; } }
{
let window = _____WB$wombat$assign$function_____("window");
let self = _____WB$wombat$assign$function_____("self");
let document = _____WB$wombat$assign$function_____("document");
let location = _____WB$wombat$assign$function_____("location");
let top = _____WB$wombat$assign$function_____("top");
let parent = _____WB$wombat$assign$function_____("parent");
let frames = _____WB$wombat$assign$function_____("frames");
let opener = _____WB$wombat$assign$function_____("opener");
function CaptionArray(len) {
this.length=len
}
Caption = new CaptionArray(499);
Caption[0] = "leaf and the ants as latterly"
Caption[1] = "thought<br>living in<br>Davis would<br>be ok"
Caption[2] = "sure arm today"
Caption[3] = "AMY<br><br>no we<br>both do<br>different<br>songs together"
Caption[4] = "much of anything she doesn't like that at all"
Caption[5] = "SUNG AS LAKE<br><br><br>that never wanted back to come"
Caption[6] = "five sound shut doors"
Caption[7] = "oh<br>my nose is<br>so<br>red<br>Obediah<br>dear"
Caption[8] = "these<br>cubes<br>have been<br>on the floor"
Caption[9] = "sweating importunate"
Caption[10] = "all over noises phone rings"
Caption[11] = "I think this is the water supply for Lake Johnsbury"
Caption[12] = "Paw so greasy"
Caption[13] = "BLACK & WHITE RAIN<br><br><br>clear water grey drops<br><br><br>on windshields in a line<br><br><br>of cars progressing slowly<br><br><br>with windshield wipers wiping"
Caption[14] = "EMILY<br><br>Roger,<br><br>are you<br><br>thinking of me"
Caption[15] = "STICKS<br><br><br>rhythm is inside the sound like another"
Caption[16] = "I think their dog always barks when coming back from the woods"
Caption[17] = "weren't there<br><br>conversations"
Caption[18] = "LOOKING AT FIRE<br><br><u>ashes</u> to ashes<br><br>looking at the fire<br><br>at has been added"
Caption[19] = "a the bank"
}
I am trying to store value of function in the variable and want to display the content in text area t1.
So every time I push the value I can get the print function in the variable s and can display content in textarea t1.
<html>
<head>
<title>Stack With Constructor </title>
</head>
<body>
<div>Stack </div>
<div>
<h1>stack</h1>
<h2>Stage1.</h2>
<p id="p1">
stack
</p>
<textarea id="t1"></textarea>
<button onclick="doJob()">push</button>
<button onclick="doJob1()">pop</button>
</div>
<textarea id="t"></textarea>
<script>
function push(v) {
if (this.st === 0) {
console.log("Stack Overflow");
} else {
this.st = this.st - 1;
this.stk[this.st] = v;
}
}
function pop() {
if (this.st === 10) {
console.log("Stack Underflow");
} else {
var temp = this.stk[this.st];
this.st = this.st + 1;
return temp;
}
}
function print() {
console.log("Printing Stack");
for (var i = this.st ; i < 10; i++) {
console.log(this.stk[i]);
}
};
function MyStack() {
this.st = 10;
this.stk = new Array(10);
this.push = push;
this.pop = pop;
this.print = print;
};
var s1 = new MyStack();
function doJob() {
var x=document.getElementById("t").value;
s1.push(x);
var s=s1.print();
document.getElementById("t1").value=s;
}
</script>
</body>
</html>
I want to display the print function in the text area t1 so it can work as interactive stack.
When I try to push value, I am getting undefined in the textarea.
change your print function like,
function print() {
console.log("Printing Stack");
var str = "";//empty string
for (var i = this.st ; i < 10; i++) {
console.log(this.stk[i]);
str+=this.stk[i]+'\n';//concatenate the value and a new line
}
return str;
};
DEMO
<html>
<head>
<title>Stack With Constructor </title>
</head>
<body>
<div>Stack </div>
<div>
<h1>stack</h1>
<h2>Stage1.</h2>
<p id="p1">
stack
</p>
<textarea id="t1"></textarea>
<button onclick="doJob()">push</button>
<button onclick="doJob1()">pop</button>
</div>
<textarea id="t"></textarea>
<script>
function push(v) {
if (this.st === 0) {
console.log("Stack Overflow");
} else {
this.st = this.st - 1;
this.stk[this.st] = v;
}
}
function pop() {
if (this.st === 10) {
console.log("Stack Underflow");
} else {
var temp = this.stk[this.st];
this.st = this.st + 1;
return temp;
}
}
function print() {
console.log("Printing Stack");
var str = "";//empty string
for (var i = this.st ; i < 10; i++) {
console.log(this.stk[i]);
str+=this.stk[i]+'\n';//concatenate the value and a new line
}
return str;
};
function MyStack() {
this.st = 10;
this.stk = new Array(10);
this.push = push;
this.pop = pop;
this.print = print;
};
var s1 = new MyStack();
function doJob() {
var x=document.getElementById("t").value;
s1.push(x);
var s=s1.print();
document.getElementById("t1").value=s;
}
function doJob1(){
s1.pop();
var s=s1.print();
document.getElementById("t1").value=s;
}
</script>
</body>
I'm practicing javascript and learning on my own. I am creating a game where you enter a text coordinates and the game tells you whether you dug something up or not. But I am trying to implement a text box so you can play out of a browser instead of the command prompt, but I'm having trouble getting the game to take the text and then run the code using it when you click on the button.
Here is the HTML for the game.
<head>
<meta charset="UTF-8">
<title>Game Board</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="board.js"></script>
<script type="text/javascript" src="game.js"></script>
</head>
<body>
<center>
<h1>Archaeology Board</h1>
Palace = 5 Spaces </br>
Temple = 4 Spaces </br>
Forum = 4 Spaces </br>
House = 3 Spaces </br>
Hut = 2 Spaces </br>
<h3>
<table id="board">
</table>
</h3>
<p>
<label for="DigBox">Enter dig coordinates:</label>
<input type="text" id="DigBox" size="3" value="" />
<input type="button" value="Dig" id="run" />
</p>
<p><input type="button" value="Restart Game" id="restart" /></p>
</center>
</body>
</html>
This is the js file to create the board.
function GameBoard()
{
this.ruins = [
{
name: "Palace",
size: 5,
successes: 0
},
{
name: "Temple",
size: 4,
successes: 0
},
{
name: "Forum",
size: 4,
successes: 0
},
{
name: "House",
size: 3,
successes: 0
},
{
name: "Hut",
size: 2,
successes: 0
}
];
this.rows = ["a", "b", "c", "d", "e", "f", "g", "h"];
this.columns = ["1", "2", "3", "4", "5", "6", "7", "8"];
this.cellMarker = 'X';
}
GameBoard.prototype.setBoard = function ()
{
var i, j, boardTags;
boardTags = "";
// build the first row of column labels
boardTags += "<tr><th> </th>";
for (j = 0; j < this.columns.length; j++) {
boardTags += "<th>" + this.columns[j] + "</th>";
}
boardTags += "</tr>";
// build the table with HTML tags
for (i = 0; i < this.rows.length; i++) {
boardTags += "<tr>";
boardTags += "<th>" + this.rows[i] + "</th>"; // row labels
for (j = 0; j < this.columns.length; j++) {
boardTags += "<td class='square' id='cell" +
this.rows[i] + this.columns[j] + "'>" + this.cellMarker + "</ td>";
}
boardTags += "</tr>";
}
$("#board").html(boardTags);
for (i = 0; i < this.ruins.length; i++) {
this.setRuin(this.ruins[i]);
}
}
GameBoard.prototype.dig = function(square, processResult)
{
var target, targetObj;
target = $("#cell"+square).attr('ruin');
if (target) {
targetObj = this.getRuin(target);
if (! $("#cell"+square).attr('dug')) {
$("#cell"+square).attr('dug', 'yes');
targetObj.successes++;
}
return targetObj;
}
else {
return undefined;
}
}
GameBoard.prototype.getRuin = function(ruinName)
{
for (var i = 0; i < this.ruins.length; i++) {
if (ruinName === this.ruins[i].name) {
return this.ruins[i];
}
}
return undefined;
}
GameBoard.prototype.randomSquare = function()
{
var colIndex = Math.floor(Math.random() * this.columns.length);
var rowIndex = Math.floor(Math.random() * this.rows.length);
return this.rows[rowIndex] + this.columns[colIndex];
}
GameBoard.prototype.setRuin = function(ruin)
{
// keeps randomly trying to place a ruin until it fits on the board
var candidateSquare = this.randomSquare();
var across = Math.random() < 0.5;
var success = this.tryPlacement(ruin, candidateSquare, across, ruin.size);
while (! success) {
candidateSquare = this.randomSquare();
across = Math.random() < 0.5;
success = this.tryPlacement(ruin, candidateSquare, across, ruin.size);
}
}
GameBoard.prototype.tryPlacement = function(ruin, square, across, size) {
var nextSquare;
if (size === 0) {
// ruin fits!
return true;
}
else if (! square) {
// invalid square
return false;
}
if (! $("#cell" + square).attr('ruin')) {
$("#cell" + square).attr('ruin', ruin.name);
// see if the rest of the ruin fits
if (this.tryPlacement(ruin, this.increment(square, across), across, size - 1)) {
// ruin fits!
return true;
}
else {
// ruin didn't fit --- undo occupied square and return false
$("#cell" + square).removeAttr('ruin');
return false
}
}
}
GameBoard.prototype.increment = function(square, across)
{
if (across) {
// need to increment the column dimension if possible
var colIndex = this.columns.indexOf(square.charAt(1));
colIndex++;
if (colIndex === this.columns.length) {
return undefined;
}
else {
return square.charAt(0) + this.columns[colIndex];
}
}
else {
// need to increment the row dimension if possible
var rowIndex = this.rows.indexOf(square.charAt(0));
rowIndex++;
if (rowIndex === this.rows.length) {
return undefined;
}
else {
return this.rows[rowIndex] + square.charAt(1);
}
}
}
This is the code I'm trying to implement in
$(function () {
tryDig = function(targetCell)
{
var targetObj = board.dig(targetCell);
if (targetObj) {
alert('Success finding the ' + targetObj.name);
$("#cell"+targetCell).html('#');
$("#cell"+targetCell).css('color', 'blue');
}
else {
alert('Failure!');
$("#cell"+targetCell).html('*').css('color', 'red');
}
}
board = new GameBoard();
board.setBoard();
});
initialize = function() {
$("#run").click(tryDig);
}
initialize = function() {
$("#restart").click(GameBoard.prototype.setBoard);
}
$(initialize);
I want to make it so whatever is in the text box, the game uses that as the coordinates to dig up in the board.
When a user inputs a sentence into the title box they are supposed to be able to generate 72 different variations of that title with words being replaced and words changing positions. The problem that is occurring is that it will not take the user input and do anything with it. It works if you pre-define the text within the array.
Below is the html used.
<html>
<head>
<title> Title Generation Module</title>
<script src="title.js" type="text/javascript"></script>
<script src="find.js" type="text/javascript"></script>
<script src="replace.js" type="text/javascript"></script>
<script src="search.js" type="text/javascript"></script>
<script src="generate.js" type="text/javascript"></script>
<!-- <script src="check.js" type="text/javascript"></script>--> <!-- Leaving for future usage not needed at this point -->
<link rel="stylesheet" type="text/css" href="title.css">
</head>
<body>
<h1>Title Generation Module</h1>
<div id="cWords">
<h3>Words That Might Return an Invalid Title</h3>
<ul>
<li>For</li>
<li>You</li>
<li>Two</li>
<li>With</li>
<li>Adaptor</li>
<li>Wireless</li>
</ul>
</div>
<!-- This allows the user to input a title -->
<h3>Input Title into Text Field</h3>
<input type="text" id="title" style="height:20px; width: 500px;">
<p>Click the Submit button. To see if the title is a good working title click on the check title button below.</p>
<button onclick="getTitle()">Submit</button>
<p id="displayTitle" class="title"></p>
<!-- This allows the user to hightllight a keyword in the Title -->
<p>Find Keywords in your sentence</p>
<input id="kText">
<button onclick="getSearch()">Search</button>
<!-- This allows the user to change the keyword within a title to a new word -->
<p>Changes You Want to Make to Keywords</p>
<input type="text" id="change">
<button onclick="newTitle()">Change Keyword</button>
<!-- Button Reloads the page -->
<button onclick="myFunction()">Reload page</button>
<!-- Reloads the page -->
<script>
function myFunction()
{
location.reload();
}
</script>
<!-- Change the Order of the Title -->
<button onclick="generate_title()">Generate Title</button>
<button onclick="displayTitle()">Display Title</button>
<script>
function displayTitle()
{
var dpTitle = document.getElementById("displayTitle").innerHTML;
alert(dpTitle);
}
</script>
</body>
</html>
Below is the javascript that will handle the function of replacing and displaying the user input.
var keyword = document.getElementById("displayTitle").innerHTML;
var kText = document.getElementById("kText").value;
var changeWord = document.getElementById("change").value;
var newKeyword = new Array(keyword);
newKeyword = keyword.split(kText).join(changeWord);
var input_keywords =
[
[check],
//[checkY,checkY],
["Cordless-","Wireless"],
["Rechargeable+"],
["you"]
].filter(function(item){
return item.length <= 80;
});
/*[
["Men", "Women", "Unisex"],
["1", "2", "3", "fourrrrrrrrrr"],
["Candy Color"],
["Spring"],
["Ski+"],
["Crochet"],
["Hip-hop"],
["Hat Beanie-"],
["One Size+"]].filter(function(item)
{
return item.length <= 80;
});
*/
/*
var input_keywords = [
["Women Men", "Men Women", "Unisex Women Men", "Unisex Men Women", "Unisex", "Womens Mens", "Mens Womens", "Unisex Womens Mens", "Unisex Mens Womens"],
["Fashion", "Trendy", "Stylish", "Korea Style"],
["Candy Color"],
["Spring", "Summer", "Winter"],
["Ski"],
["Crochet", "Knit", "Knitted"],
["Elastic", "Strechable"],
["Hip-hop", "Dance"],
["Hat", "Cap", "Beanie", "Hat Cap", "Hat Beanie", "Hat Cap Beanie"],
["One Size"]
].filter(function(item){
return item.length <= 80;
});
*/
var limit_count = 1;
var max_char_per_title = 80;
var sub_library = ["for=4", "you=u", "at=#", "two=2", "with=w", "adapter=adpt", "Monokini=Mono 9"].map( function (item)
{ return item.split("=");});
function calc_length(title)
{
return (title
.join(" ") + " ")
.replace("- ", " ")
.replace("+ ", " ")
.replace("* ", " ")
.replace(" ", " ")
.replace("\" ", " ")
.replace(" \"", " ")
.length - 1;
}
function get_all_titles(keywords)
{
var result_titles = [];
for(var i = 0; i < keywords.length; i ++)
{
var word_count = keywords[i].length;
var words = keywords[i];
var previous_count = result_titles.length;
if (previous_count == 0)
{
previous_count = word_count;
for (var sub_ii = 0 ; sub_ii < word_count; sub_ii++)
{
result_titles[sub_ii] = [];
result_titles[sub_ii][i] = words[sub_ii];
}
}
else
{
for (var sub_i = 0; sub_i < word_count; sub_i++)
{
for (var sub_ii = 0 ; sub_ii < previous_count; sub_ii++)
{
if (result_titles[previous_count * sub_i + sub_ii] == undefined)
{
result_titles[previous_count * sub_i + sub_ii] = result_titles[sub_ii ].slice();
}
result_titles[previous_count * sub_i + sub_ii][i] = words[sub_i];
}
}
}
}
return result_titles;
}
function substitute(title)
{
for (var subs_idx = 0 ; subs_idx < sub_library.length; subs_idx++)
{
var index = title.indexOf(sub_library[subs_idx][0]);
if (index >= 0)
{
title[index] = sub_library[subs_idx][1];
}
}
return title;
}
function shorten_title_length(titles)
{
var result = [];
var count = 0;
for (var i = 0 ; i < titles.length; i++)
{
if (calc_length(titles[i]) > max_char_per_title)
{
//substitute with the word in library
titles[i] = substitute(titles[i]);
// still too long, remove possible words.
if (calc_length(titles[i]) > max_char_per_title)
{
var words = titles[i];
for (var word_idx = 0 ; word_idx < words.length; word_idx++)
{
if (words[word_idx].indexOf("/") == (words[word_idx].length - 1))
{
titles[i] = titles[i].splice(word_idx, 1);
}
}
titles[i] = words
}
}
if (calc_length(titles[i]) <= max_char_per_title)
{
result[count] = titles[i];
count++;
}
else
{
console.log(titles[i].join(" \ "));
}
}
return result;
}
function change_forward_position(title)
{
var words = title;
for (var word_idx = 0 ; word_idx < words.length; word_idx++)
{
if (words[word_idx][words[word_idx].length - 1] == "-")
{
if (word_idx != words.length - 1)
{
var tmp = words[word_idx];
words[word_idx] = words[word_idx + 1];
words[word_idx + 1] = tmp;
word_idx ++;
}
}
}
title = words;
return title;
}
function change_backward_position(title)
{
var words = title;
for (var word_idx = 0 ; word_idx < words.length; word_idx++)
{
if (words[word_idx][words[word_idx].length - 1] == "+")
{
if (word_idx != 0)
{
var tmp = words[word_idx];
words[word_idx] = words[word_idx - 1];
words[word_idx - 1] = tmp;
}
}
}
title = words;
return title;
}
function finalize(titles)
{
for (var title_idx = 0 ; title_idx < titles.length; title_idx++)
{
for (var word_idx = 0 ; word_idx < titles[title_idx].length; word_idx++)
{
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '+')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '-')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '/')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '"')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '*')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
}
}
return titles;
}
function generate_title()
{
var all_titles = get_all_titles(newKeyword);
//Check keyword files provided by the user, that optional sub words are at least 24
if (all_titles.length < limit_count)
{
alert("not enough different titles");
}
//check total char per title
all_titles = shorten_title_length(all_titles);
// substitute half randomly.
for (var i = 0 ; i < all_titles.length; i++)
{
if (Math.random() > 0.5)
{
all_titles[i] = substitute(all_titles[i]);
}
}
//changing position backward.
for (var i = 0 ; i < all_titles.length; i++)
{
if (Math.random() > 0.5)
{
all_titles[i] = change_backward_position(all_titles[i]);
}
}
//changing position forward.
for (var i = 0 ; i < all_titles.length; i++)
{
if (Math.random() > 0.5)
{
all_titles[i] = change_forward_position(all_titles[i]);
}
}
all_titles = finalize(all_titles);
// evaluate.....
for (var i = 0 ; i < all_titles.length; i++)
{
console.log(i);
console.log(all_titles[i].join(" \ "));
console.log(all_titles[i].length);
alert(all_titles);
}
}
I would like to update a chart (made with angular-nvd3) each time some options are changed :
here are my options :
(in the code, it looks like this :
<input type="radio" ng-model="mode" value="actions"><strong ng-show="actions.length !== 0"> Actions :</strong><br />
<span class="retrait" ng-repeat = "action in actions">
<input type="checkbox" ng-model="actions[$index].value" ng-disabled="mode != 'actions'"> {{action.statut}}<br />
</span><br />
<input type="radio" ng-model="mode" value="jalons"><strong ng-show="jalons.length !== 0"> Jalons :</strong><br />
<span class="retrait" ng-repeat = "jalon in jalons">
<input type="checkbox" ng-model="jalons[$index].value" ng-disabled="mode != 'jalons'"> {{jalon.statut}}<br />
</span><br />
First, i tried to make a filter, but my filter had to access scope values (to see what options were checked), so i had to use "this" into the filter. The issue is that when updating the graph, it changes the model and re-lauches the filter : it makes an infinite loop.
So I decided to make, a pseudo filter, with a function in the controller.
Here is my function :
$scope.generateData = function() {
var liste = [];
var i, j, k, n, p, dataStock;
dataStock = [
{"key":{'jalons':'Non atteint', 'actions':'Non fait', 'phases':'Non fait'}[$scope.mode],"values":[]},
{"key":{'jalons':'Atteint', 'actions':'En cours', 'phases':'En cours'}[$scope.mode],"values":[]},
{"key":{'jalons':'Validé', 'actions':'Fait', 'phases':'Fait'}[$scope.mode],"values":[]}
];
var stock_retards_ouverture = [];
var stock_retards_fermeture = [];
var flux_retards_ouverture = [];
var flux_retards_fermeture = [];
var stock_non_faite = [];
var stock_faite = [];
var stock_en_cours = [];
var flux_non_faite = [];
var flux_faite = [];
var flux_en_cours = [];
var num_serie = parseInt($scope.serie.substring($scope.serie.length-1, $scope.serie.length), 10);
i=1;
while(i<=num_serie) {
stock_retards_ouverture.push(0);
stock_retards_fermeture.push(0);
flux_retards_ouverture.push(0);
flux_retards_fermeture.push(0);
stock_non_faite.push(0); // pour les jalons, c'est le statut non atteint
stock_faite.push(0); // pour les jalons, validé
stock_en_cours.push(0); // pour les jalons, atteint
flux_non_faite.push(0);
flux_faite.push(0);
flux_en_cours.push(0);
i+=1;
}
for(i = 0; i<$scope.raw_data.length; i++) {
var element = $scope.raw_data[i];
var type = element.type;
var root = element.root;
var statut = element[$scope.serie].statut;
// pour les phases
if($scope.mode === 'phases') {
if(type == $scope.sauvegarde.taches_types.phase) {
for(j = 0; j< $scope.phases.length; j++) {
if($scope.phases[j].statut == statut && $scope.phases[j].value === true) {
for(k = 0; k<$scope.affichage.length;k++){
if(root == $scope.affichage[k].projet && $scope.affichage[k].value === true){
liste.push(element);
// pour chaque série
for(p=1;p<=num_serie;p++) {
if(element['serie'+p].statut === $scope.sauvegarde.taches_statuts.phase_en_cours) {
stock_en_cours[p-1] += 1;
}
if(element['serie'+p].statut === $scope.sauvegarde.taches_statuts.phase_faite) {
stock_faite[p-1] += 1;
}
if(element['serie'+p].statut === $scope.sauvegarde.taches_statuts.phase_non_faite) {
stock_non_faite[p-1] += 1;
}
}
}
}
}
}
}
}
// pour les actions
if($scope.mode === 'actions') {
if(type == $scope.sauvegarde.taches_types.action) {
for(j = 0; j< $scope.actions.length; j++) {
if($scope.actions[j].statut == statut && $scope.actions[j].value === true) {
for(k = 0; k<$scope.affichage.length;k++){
if(root == $scope.affichage[k].projet && $scope.affichage[k].value === true){
liste.push(element);
// pour chaque série
for(p=1;p<=num_serie;p++) {
if(element['serie'+p].statut === $scope.sauvegarde.taches_statuts.action_en_cours) {
stock_en_cours[p-1] += 1;
}
if(element['serie'+p].statut === $scope.sauvegarde.taches_statuts.action_faite) {
stock_faite[p-1] += 1;
}
if(element['serie'+p].statut === $scope.sauvegarde.taches_statuts.action_non_faite) {
stock_non_faite[p-1] += 1;
}
}
}
}
}
}
}
}
// pour les jalons
if($scope.mode === 'jalons') {
if(type == $scope.sauvegarde.taches_types.jalon) {
for(j = 0; j< $scope.jalons.length; j++) {
if($scope.jalons[j].statut == statut && $scope.jalons[j].value === true) {
for(k = 0; k<$scope.affichage.length;k++){
if(root == $scope.affichage[k].projet && $scope.affichage[k].value === true){
liste.push(element);
// pour chaque série
for(p=1;p<=num_serie;p++) {
if(element['serie'+p].statut === $scope.sauvegarde.taches_statuts.jalon_atteint) {
stock_en_cours[p-1] += 1;
}
if(element['serie'+p].statut === $scope.sauvegarde.taches_statuts.jalon_valide) {
stock_faite[p-1] += 1;
}
if(element['serie'+p].statut === $scope.sauvegarde.taches_statuts.jalon_non_atteint) {
stock_non_faite[p-1] += 1;
}
}
}
}
}
}
}
}
}
$scope.stock_retards_ouverture = stock_retards_ouverture;
$scope.stock_retards_fermeture = stock_retards_fermeture;
$scope.flux_retards_ouverture = flux_retards_ouverture;
$scope.flux_retards_fermeture = flux_retards_fermeture;
$scope.stock_non_faite = stock_non_faite;
$scope.stock_faite = stock_faite;
$scope.stock_en_cours = stock_en_cours;
$scope.flux_non_faite = flux_non_faite;
$scope.flux_faite= flux_faite;
$scope.flux_en_cours = flux_en_cours;
for(i=0;i<num_serie;i++) {
var lastElem1 = {};
var lastElem2 = {};
var lastElem3 = {};
if(dataStock[0].values.length === 0) {
lastElem1.y1 = 0;
lastElem2.y1 = 0;
lastElem3.y1 = 0;
} else {
lastElem1 = dataStock[0].values[dataStock[0].values.length - 1];
lastElem2 = dataStock[1].values[dataStock[1].values.length - 1];
lastElem3 = dataStock[2].values[dataStock[2].values.length - 1];
}
var elem0 = {
x: "serie"+(i+1),
y: stock_faite[i],
y0: lastElem1.y1,
series: i,
size: stock_faite[i],
y1: lastElem1.y1 + stock_faite[i]
};
var elem1 = {
x: "serie"+(i+1),
y: stock_en_cours[i],
y0: lastElem2.y1,
series: i,
size: stock_en_cours[i],
y1: lastElem2.y1 + stock_en_cours[i]
};
var elem2 = {
x: "serie"+(i+1),
y: stock_non_faite[i],
y0: lastElem3.y1,
series: i,
size: stock_non_faite[i],
y1: lastElem3.y1 + stock_non_faite[i]
};
dataStock[0].values.push(elem0);
dataStock[1].values.push(elem1);
dataStock[2].values.push(elem2);
}
return dataStock;
};
It generates the proper data, which can be used to create the graph.
Then, for the graph, I used the awesome library Angular-nvd3 :
<div class="graphCtrl" id="graph1">
<h3 class="graphTitle">Suivi des actions (Stock)</h3>
<nvd3 options="options" data="generateData()"></nvd3>
</div>
Where get the data from my function.
But I don't get why, I still have the infinite loop of $digest, as I can still see the issue :
Error: [$rootScope:infdig]
Do you know where it could come from ?
I think the problem is here
<div class="graphCtrl" id="graph1">
<h3 class="graphTitle">Suivi des actions (Stock)</h3>
<nvd3 options="options" data="generateData()"></nvd3>
</div>
you see, every time the $digest process runs the function will be executed and this function will change model which triggers $digest and so on, that's your infinite loop, best to do is to assign generated data to variable and use it then in html
<div class="graphCtrl" id="graph1">
<h3 class="graphTitle">Suivi des actions (Stock)</h3>
<nvd3 options="options" data="myGeneratedData"></nvd3>
</div>
js
$scope.myGeneratedData = $scope.generateData()
or just generatedData() as it doesn't have to be on $scope