Overwrite results of one function with another - javascript

I am trying to create a simple encoder-decoder game which encodes and decodes user-entered word as shown below:
eg. overflow --> ofvleorw --> overflow (userword --> encodedword
--> decodedword).
The issue I'm having is that the encoder part works fine but when clicking decode button, the developer tools crashes after few seconds. I am unsure what the real issue is as I see no error messages on console so my only guess is the title heading.
Thank You and Happy New Year 2017
function encoder(){
var userWord = document.getElementById("userinputbox").value; // gets user entered word
var letterArray = userWord.split("");
var encodedWord = [];
for (var i=0; i<letterArray.length/2; i++) {
encodedWord.push(letterArray[i],letterArray[letterArray.length/2 + i]);
} // pushing elements sequentially from first and second half of original array to new empty array
displayResult.value = encodedWord.join("");
}
function decoder() {
var encodedWord = displayResult.value; // extracts the encoded text from display box
var letterArray = encodedWord.split("");
var half1 = [], half2 = []; // array for storing even and odd index elements from letterArray
for (var i=0; i<letterArray.length; i+2) {
half1.push(letterArray[i]);
half2.push(letterArray[i+1]);
}
var decodedWord = half1.concat(half2);
displayResult.value = decodedWord.join(""); // overwriting the displaybox with new string
}
var displayResult = document.getElementById('displaybox'); // box to show results
var encodeBtn = document.getElementById('encode'); // event-listener 'Encode' btn
encodeBtn.addEventListener("click", encoder);
var decodeBtn = document.getElementById('decode'); // event-listener 'Decode' btn
decodeBtn.addEventListener("click", decoder);
<body>
Enter word (even number of letters) :<input type="text" id="userinputbox"><br>
<input type="button" value="Encode" id="encode">
<input type="button" value="Decode" id="decode">
Results :<input type="text" id="displaybox" value="">
</body>

Your for loop is infinite: for (var i=0; i<letterArray.length; i+2)
You probably wanted something like i = i + 2 in the end.
Whenever JS dies and you don't see an error, it's likely an infinite loop happening somewhere.
Happy new year !

Related

How to match exact numerical pattern using FlexSearch

Is there a way to have FlexSearch (https://github.com/nextapps-de/flexsearch) find only results that contains exact character sequence including numerical characters ?
The documentation is there : https://flexsearch.net/docs/flexsearch-manual.pdf
There is a section page 35 called Analyzer that seems to give hints on how to do, but there is a TODO note at the end when is expected the list of Analyzer that we could try alternatively.
The following thread works fine only for plain characters : https://stackoverflow.com/a/69677055/2143734
Or if you know any equivalent efficient and browser compatible search API, it is just that I seem to miss something there !
If you input C3, 1, C0 or 4, you get results although none of these numbers appears...
var data = Array.from(Array(1000000).keys()).map(String);
data.unshift("CA", "VIS-CD", "CATDIR-U", "UE5", "GAE");
(function() {
const index = new FlexSearch.Index({
tokenize: "full",
matcher: "default",
cache: true
});
for (var i = 0; i < data.length; i++) {
index.add(i, data[i]);
}
var suggestions = document.getElementById("suggestions");
var userinput = document.getElementById("userinput");
userinput.addEventListener("input", show_results, true);
function show_results() {
var value = this.value;
var results = index.search(value);
var entry, childs = suggestions.childNodes;
var i = 0,
len = results.length;
for (; i < len; i++) {
entry = childs[i];
if (!entry) {
entry = document.createElement("div");
suggestions.appendChild(entry);
}
entry.textContent = data[results[i]];
}
while (childs.length > len) {
suggestions.removeChild(childs[i])
}
}
}());
<!doctype html>
<html>
<head>
<title>FlexSearch Sample</title>
<script src="https://cdn.jsdelivr.net/gh/nextapps-de/flexsearch#master/dist/flexsearch.compact.js"></script>
</head>
<body>
<input type="text" id="userinput" placeholder="Search by keyword...">
<br></br>
<div id="suggestions"></div>
</body>
</html>
find only results that contains exact character sequence
ok, so instead of Array.prototype.includes logic, I used a cache system for the kind of search you want :D
var data = Array.from(Array(1000000).keys()).map(String);
data.unshift("CA", "VIS-CD", "CATDIR-U", "UE5", "GAE");
//in essence, you can just change the condition(match_condition) to append a result based on whatever other condition you want
//the edit has me changing the match condition :D
//the edit also has me attempting a cache block(for speed)
(function() {
var suggestions = document.getElementById("suggestions");
var userinput = document.getElementById("userinput");
var cacheText={}, resultLimit=100, length=Symbol(null) //I'm doing caching based on how you want results(as in your snippet this part will lag a bit)
for(let i=0;i<data.length;i++){
if(typeof data[i]!="string"){continue}
for(let j=0;j<data[i].length;j++){
let string="" //for caching all direct text indexes
for(let k=0;k<=j;k++){string+=data[i][k]}
if(!cacheText[string]){
cacheText[string]={[data[i]]:true}
cacheText[string][length]=1 //length measurement
}
else{
if(cacheText[string][length]==resultLimit){continue}
cacheText[string][data[i]]=true
cacheText[string][length]++ //adding to length
}
}
}
userinput.addEventListener("input", show_results, true);
function show_results() {
var {value}=this, values={}
let match_condition=(text)=> cacheText[value]?cacheText[value][text]:false && value!="" //match condition(that you can change to whatever other logic)
for(let i=0; i<suggestions.children.length; i++){
//the purpose of this loop is to only remove elements that won't be on the new result list
let matchCondition=()=>
!suggestions.children[i]? true: //test(if child still exists)
match_condition(suggestions.children[i].innerText) //condition(in this case if data exactly includes user input)
while(!matchCondition()){ suggestions.children[i].remove() } //remove only those which won't match up to the condition
if(!suggestions.children[i]){break} //end loop(since if this is true, there is no child left)
values[suggestions.children[i].innerText]=true //to indicate that this value already exists when doing the second loop below
}
for(let i=0; i<data.length; i++){
//the purpose of this loop is to append UNIQUE results
if(match_condition(data[i]) && !values[data[i]]){
var child=document.createElement('div')
child.innerText=data[i]
suggestions.appendChild(child)
}
}
}
}());
<body>
<input type="text" id="userinput" placeholder="Search by keyword..." />
<br></br>
<div id="suggestions"></div>
</body>

How to process a text in order to create a new array with some sub strings?

I am writing a script on html, the idea is that I want to process a text that looks like this:
"TW|223SDSDr33|Archive" "Yes"
"TW|ASFFSDFSFASDFS|Name" "LOCALggr"
"TW|AFFSFSFSDFSFASDFS|AFFAckAssocCd" ""
"TW|12AFFFSDFASFSFASDFS|AFFAckCommID" "fsdf"
"TW|FSFASFFSDFSFASDFS|AFFAckLevel" "fsdf Supported"
"TW|AFFSDFAASFSA|AFFAckRqst" "No Requedfst"
"TW|AFFSDFSFASDFS|AFFAckTestInd" "Test"
"TW|sfasfsSFSAFAS|AFFAckVersion" "fsdfs"
I want to process the text to create an array called words, that contains substrings of the previous text using the pipe as separator as follows:
words=["TW,223SDSDr33,Archive" "Yes",...,"TW,sfasfsSFSAFAS,AFFAckVersion" "fsdfs"]
In order to achieve this, I tried:
var stringArray = document.getElementById("texto").value.split('\n');
document.write(stringArray.toString());
var arrayLength = stringArray.length;
for (var i = 0; i < arrayLength; i++) {
//Process every line;
}
This save my textarea to then process it, but the problem is that I don't know how to process every line in order to extract the sub strings that I want, In order to be more clear this is the complete code, I would like to appreciate any suggestion to achieve this, thanks thanks anyhow:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<textarea cols=150 rows=10 id="texto">
"TW|223SDSDr33|Archive" "Yes"
"TW|ASFFSDFSFASDFS|Name" "LOCALggr"
"TW|AFFSFSFSDFSFASDFS|AFFAckAssocCd" ""
"TW|12AFFFSDFASFSFASDFS|AFFAckCommID" "fsdf"
"TW|FSFASFFSDFSFASDFS|AFFAckLevel" "fsdf Supported"
"TW|AFFSDFAASFSA|AFFAckRqst" "No Requedfst"
"TW|AFFSDFSFASDFS|AFFAckTestInd" "Test"
"TW|sfasfsSFSAFAS|AFFAckVersion" "fsdfs"
</textarea>
<script>
var words = [];
var stringArray = document.getElementById("texto").value.split('\n');
document.write(stringArray.toString());
var arrayLength = stringArray.length;
for (var i = 0; i < arrayLength; i++) {
//Do something;
}
</script>
</body>
</html>
I used both a regular expression and Array.prototype.split. You can uncomment depending what you want to put into words.
for (var i = 0; i < arrayLength; i++) {
var line = stringArray[i];
var quotes = /"(.*?)" "(.*?)"/.exec(line);
if (quotes) {
var first = quotes[1];
var last = quotes[2];
var separated = first.split("|");
// If you want to put the array of words
words.push(separated);
// In case you want them joined with a colon
// words.push(separated.join(","));
// If you want to add the second word that was in double quotes
// words.push(last);
}
}
// Uncomment to see results
// console.log(words);

Javascript's getElementById is not working in my loop

I have an issue with a function I have been working on. The purpose of this function is to take the dates that are inside two sets of text input boxes, calculate the difference between the two, and then place that number of days in a third set of boxes. My function is shown below.
function daysBetween() {
for (var i = 0; i < 8; i++) {
//Get the value of the current form elements
var start = namestart[i];
var end = namend[i];
var out = names[i];
//Duration of a day
var d = 1000*60*60*24;
// Split Date one
var x = start.split("-");
// Split Date two
var y = end.split("-");
/// // Set Date one object
var d1 = new Date(x[0],(x[1]-1),x[2]);
// // Set Date two object
var d2 = new Date(y[0],(y[1]-1),y[2]);
//
// //Calculate difference
diff = Math.ceil((d2.getTime()-d1.getTime())/(d));
//Show difference
document.getElementById(out).value = diff;
}
}
The three arrays referenced by the variables at the beginning contain simply the names of the form elements I wish to access. I've tested the start, end, and out variables with an alert box and the loop runs fine if I do not have the line under the Show Difference comment in the code. I have also gone through and made sure that all names match and they do. Also I have manually run the page eight times (there is eight sets of boxes) with each set of names and it successfully displays 'NaN' in the day box (I have no data in the source boxes as of yet so NaN is the expected behaviour).
When I run the function as shown here what happens is that the first set of text boxes works as intended. Then the loop stops. So my question is quite simple, why does the loop hangup with getElementById even though the names[0] value works, it finds the text box and puts the calculated difference in the box. The text box for names[1] does not work and the loop hangs up.
If you need more detailed code of my text boxes I can provide it but they follow the simple template below.
// namestart[] array
<input type="text" name="start_date_one" id="start_date_one" value=""/> <br />
// namend[] array
<input type="text" name="end_date_one" id="end_date_one" value=""/> <br />
// names[] array
<input type="text" name="day_difference_one" id="day_difference_one" value=""/>
Thanks for any help in advance.
Edit: Noticing the comments I figured I would add my array definitions for refernece. These are defined immediately above the function in my calcdate.js file.
var namestart = new Array ();
namestart[0] = "trav_emer_single_date_go";
namestart[1] = "trav_emer_extend_date_go";
namestart[2] = "allinc_single_date_go";
namestart[3] = "allinc_annual_date_go";
namestart[4] = "cancel_date_go";
namestart[5] = "visitor_supervisa_date_go";
namestart[6] = "visitor_student_date_go";
namestart[7] = "visitor_xpat_date_go";
var namend = new Array ();
namend[0] = "trav_emer_single_date_ba";
namend[1] = "trav_emer_extend_date_ba";
namend[2] = "allinc_single_date_ba";
namend[3] = "allinc_annual_date_ba";
namend[4] = "cancel_date_ba";
namend[5] = "visitor_supervisa_date_ba";
namend[6] = "visitor_student_date_ba";
namend[7] = "visitor_xpat_date_ba";
var names = new Array ();
names[0] = "trav_emer_single_days";
names[1] = "trav_emer_extend_days";
names[2] = "allinc_single_days";
names[3] = "allinc_annual_days";
names[4] = "cancel_days";
names[5] = "visitor_supervisa_days";
names[6] = "visitor_student_days";
names[7] = "visitor_xpat_days";
I reference the file and call my function in my header as such:
<script type="text/javascript" src="calcdate.js"></script>
<script type="text/javascript">
window.onload = daysBetween;
</script>
First and foremost, you can't reference an object by its ID when it doesn't have an ID.
<input type="text" id="start_date_one" name="start_date_one" />
since you say out contains a name you might want to change
document.getElementById(out).value = diff;
to
document.getElementsByName(out)[0].value = diff;
or you could actually just add the id attribute to your html and set it to the same value as the name attribute and you can avoid changing your javascript.
getElementById gets the element by its id attribute, getElementsByName gets all of the elements with the specified name attribute and returns it as an array. In HTML id is supposed to be unique which is why getElementById returns only 1 element

Adding names to an array and outputting them to a table

I'm having some trouble getting my code to work. This is what I have so far.
function outputNamesAndTotal() {
var name;
var outputTable;
var inputForm;
var nameArray;
var outputDiv;
outputDiv = document.getElementById("outputDiv");
inputForm = document.getElementById("inputForm");
outputTable = document.getElementById("outputTable");
name = inputForm.name.value;
nameArray = [];
nameArray.push(name);
for (var i = 0; i > nameArray.length; i++) {
outputTable.innerHTML += "<tr>" + nameArray[i] + "</tr>";
}
inputForm.name.focus();
inputForm.name.select();
return false;
}
When I add the loop it breaks the code completely, but I can't figure out why.
What I'm trying to do is use an HTML form to get a name from the user. Once the user enters the name, the program adds the name to the array, and outputs each array entry to a row in a table.
It's pretty basic, but it's still giving me all kinds of trouble!
I think you are clearing your array of names every time you call the function. You should bring the line:
nameArray = [];
out and make it global.
I ran a quick test and the following code works in at least FireFox
Edited to use appendChild
<html>
<head>
<script type='text/javascript'>
var names = [];
function addName() {
var nameTxt = document.getElementById('name_txt');
var name = nameTxt.value;
names.push(name);
var outTable = document.getElementById('out_tbl');
var row = document.createElement('tr');
var entry = document.createElement('td');
var txt = document.createTextNode(name);
entry.appendChild(txt);
row.appendChild(entry);
outTable.appendChild(row);
var numDiv = document.getElementById('num_div');
removeAllChildren(numDiv);
var numTxt = document.createTextNode('You have ' + names.length + ' names');
numDiv.appendChild(numTxt);
}
function removeAllChildren(e) {
while (e.hasChildNodes()) {
e.removeChild(e.firstChild);
}
}
</script>
</head>
<body>
<table id='out_tbl'>
</table>
<div id='num_div'>You have 0 names</div>
<input id='name_txt' type='text'/>
<button onclick="addName()">CLICK</button>
</body>
</html>
Edit: Oh yeah and you are the fact that you are looping through the array every time. If you "globalize" the name array, you're gonna print the whole array every time you add a name.
Edit x2: the code you originally posted had nameArray as a local variable inside the function. This effectively clears the array every time you call the function. Then every time you call the function you add the current name to the now empty array, and loop through all 1 (one) elements that the array now holds.
What you want to do is "globalize" the name array, and remove the loop from your function. This will allow you to build up your name array across multiple calls, and works the way that you want it.
Also, innerHTML is not really the best way to add things to the page. I would suggest using appendChild().
-C
for (var i = 0; i > nameArray.length; i++) {
I think you mean i < nameArray.length

Javascript dynamic array of strings

Is there a way to create a dynamic array of strings on Javascript?
What I mean is, on a page the user can enter one number or thirty numbers, then he/she presses the OK button and the next page shows the array in the same order as it was entered, one element at a time.
Code is appreciated.
What I mean is, on a page the user can enter one number or thirty numbers, then he/she presses the OK button and the next page shows the array in the same order as it was entered, one element at a time.
Ok, so you need some user input first? There's a couple of methods of how to do that.
First is the prompt() function which displays a popup asking the user for some input.
Pros: easy. Cons: ugly, can't go back to edit easily.
Second is using html <input type="text"> fields.
Pros: can be styled, user can easily review and edit. Cons: a bit more coding needed.
For the prompt method, collecting your strings is a doddle:
var input = []; // initialise an empty array
var temp = '';
do {
temp = prompt("Enter a number. Press cancel or leave empty to finish.");
if (temp === "" || temp === null) {
break;
} else {
input.push(temp); // the array will dynamically grow
}
} while (1);
(Yeah it's not the prettiest loop, but it's late and I'm tired....)
The other method requires a bit more effort.
Put a single input field on the page.
Add an onfocus handler to it.
Check if there is another input element after this one, and if there is, check if it's empty.
If there is, don't do anything.
Otherwise, create a new input, put it after this one and apply the same handler to the new input.
When the user clicks OK, loop through all the <input>s on the page and store them into an array.
eg:
// if you put your dynamic text fields in a container it'll be easier to get them
var inputs = document.getElementById('inputArea').getElementsByTagName('input');
var input = [];
for (var i = 0, l = inputs.length; i < l; ++i) {
if (inputs[i].value.length) {
input.push(inputs[i].value);
}
}
After that, regardless of your method of collecting the input, you can print the numbers back on screen in a number of ways. A simple way would be like this:
var div = document.createElement('div');
for (var i = 0, l = input.length; i < l; ++i) {
div.innerHTML += input[i] + "<br />";
}
document.body.appendChild(div);
I've put this together so you can see it work at jsbin
Prompt method: http://jsbin.com/amefu
Inputs method: http://jsbin.com/iyoge
var junk=new Array();
junk.push('This is a string.');
Et cetera.
As far as I know, Javascript has dynamic arrays. You can add,delete and modify the elements on the fly.
var myArray = [1,2,3,4,5,6,7,8,9,10];
myArray.push(11);
document.writeln(myArray); // Gives 1,2,3,4,5,6,7,8,9,10,11
var myArray = [1,2,3,4,5,6,7,8,9,10];
var popped = myArray.pop();
document.writeln(myArray); // Gives 1,2,3,4,5,6,7,8,9
You can even add elements like
var myArray = new Array()
myArray[0] = 10
myArray[1] = 20
myArray[2] = 30
you can even change the values
myArray[2] = 40
Printing Order
If you want in the same order, this would suffice. Javascript prints the values in the order of key values. If you have inserted values in the array in monotonically increasing key values, then they will be printed in the same way unless you want to change the order.
Page Submission
If you are using JavaScript you don't even need to submit the values to the different page. You can even show the data on the same page by manipulating the DOM.
You can go with inserting data push, this is going to be doing in order
var arr = Array();
function arrAdd(value){
arr.push(value);
}
Here is an example. You enter a number (or whatever) in the textbox and press "add" to put it in the array. Then you press "show" to show the array items as elements.
<script type="text/javascript">
var arr = [];
function add() {
var inp = document.getElementById('num');
arr.push(inp.value);
inp.value = '';
}
function show() {
var html = '';
for (var i=0; i<arr.length; i++) {
html += '<div>' + arr[i] + '</div>';
}
var con = document.getElementById('container');
con.innerHTML = html;
}
</script>
<input type="text" id="num" />
<input type="button" onclick="add();" value="add" />
<br />
<input type="button" onclick="show();" value="show" />
<div id="container"></div>
The following code creates an Array object called myCars:
var myCars=new Array();
There are two ways of adding values to an array (you can add as many values as you need to define as many variables you require).
1:
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
You could also pass an integer argument to control the array's size:
var myCars=new Array(3);
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
2:
var myCars=new Array("Saab","Volvo","BMW");
Note: If you specify numbers or true/false values inside the array then the type of variables will be numeric or Boolean instead of string.
Access an Array
You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.
The following code line:
document.write(myCars[0]);
will result in the following output:
Saab
Modify Values in an Array
To modify a value in an existing array, just add a new value to the array with a specified index number:
myCars[0]="Opel";
Now, the following code line:
document.write(myCars[0]);
will result in the following output:
Opel
Please check http://jsfiddle.net/GEBrW/ for live test.
You can use similar method for dynamic arrays creation.
var i = 0;
var a = new Array();
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
The result:
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
a[4] = 5
a[5] = 6
a[6] = 7
a[7] = 8
Just initialize an array and push the element on the array.
It will automatic scale the array.
var a = [ ];
a.push('Some string'); console.log(a); // ['Some string']
a.push('another string'); console.log(a); // ['Some string', 'another string']
a.push('Some string'); console.log(a); // ['Some string', 'another string', 'Some string']

Categories

Resources