I want to record the time between each keystroke (just one key to start with, the 'A' key) in millseconds.
After the user finishes his thing he can submit and check out the timings between each key stroke. Like:
1: 500
2: 300
3: 400
4: 500
5: 100
6: 50
7: 50
8: 25
I believe this is possible with Javascript, is it?
Sure:
var times = [];
// add an object with keycode and timestamp
$(document).keyup(function(evt) {
times.push({"timestamp":evt.timeStamp,
"keycode":evt.which})
});
// call this to get the string
function reportTimes() {
var reportString = "";
for(var i = 0; i < times.length - 1; ++i) {
reportString += (i+1) + ": " + (times[i+1].timestamp - times[i].timestamp) + " ";
}
return reportString; // add this somewhere or alert it
}
I added the keycode just in case you wanted it later; it's not necessary for your exact problem statement.
Clarification from comments discussion:
The for loop only goes to up to times.length - 2 (since i is always strictly less than times.length - 1), so there is no issue about times[i+1] being outside the bounds of the array. For example, if you do five key presses and therefore have a times array with five elements (indexed from 0 to 4):
1st pass: times[1].timestamp - times[0].timestamp
2nd pass: times[2].timestamp - times[1].timestamp
3rd pass: times[3].timestamp - times[2].timestamp
4th pass: times[4].timestamp - times[3].timestamp
Then the loop terminates, because setting i to 4 triggers the termination condition:
= i < times.length - 1
= 4 < 5 - 1
= 4 < 4
= false [i cannot be set to 4 by this loop]
Thus, times[i+1] is always a validly indexed element, because i is at most one less than the maximum index.
Related
I try using The google diff-match-path library for line diffs:
https://github.com/google/diff-match-patch/wiki/Line-or-Word-Diffs. I get wrong patches when in sum the lines of both inputs goes beyond 65,536 (2^16) lines.
Is that a bug (in my code or diff-match-patch), or am I hitting a known limitation of javascript/nodejs? Anything I can do to use d-m-p with larger files?
Using node version v6.3.1, diff-match-patch 1.0.4
This script reproduces the problem
var diff_match_patch = require("diff-match-patch")
// function copied from google wiki
// https://github.com/google/diff-match-patch/wiki/Line-or-Word-Diffs
function diff_lineMode(text1, text2) {
var dmp = new diff_match_patch();
var a = dmp.diff_linesToChars_(text1, text2);
var lineText1 = a.chars1;
var lineText2 = a.chars2;
var lineArray = a.lineArray;
var diffs = dmp.diff_main(lineText1, lineText2, false);
dmp.diff_charsToLines_(diffs, lineArray);
return diffs;
}
// reproduce problem by diffing string with many lines to "abcd"
for (let size = 65534; size < 65538; size += 1) {
let text1 = "";
for (let i = 0; i < size; i++) {
text1 += i + "\n";
}
var patches = diff_lineMode(text1, "abcb")
console.log("######## Size: " + size + ": patches " + patches.length)
for (let i = 0; i < patches.length; i++) {
// patch[0] is action, patch[1] is value
var action = patches[i][0] < 0 ? "remove" : (patches[i][0] > 0 ? "add" : "keep")
console.log("patch" + i + ": " + action + "\n" + patches[i][1].substring(0, 10))
}
}
Giving these outputs:
######## Size: 65534: patches 2
patch0: remove
0
1
2
3
4
patch1: add
abcb
######## Size: 65535: patches 2
patch0: remove
0
1
2
3
4
patch1: add
######## Size: 65536: patches 2
patch0: keep
0
patch1: remove
1
2
3
4
5
######## Size: 65537: patches 3
patch0: remove
0
patch1: keep
1
patch2: remove
2
3
4
5
6
It's a limitation from ES5 and the algorithm mapping lines to 16bit unicode characters. On ES6, it can be extended to 2^21 bit instead, covering longer files.
To speed up line-diffing, the algorithm does not compare the whole texts, but replaces each line with a single unicode character. So each character in the replacement maps to one unique line in a hashmap. The number of unicode characters however is limited, and the current implementation merely overflows.
This will not cause false positives (same lines will still be considered same), but it may miss some line differences at a low probability of 1/65K per line for natural diffs.
And it prevents the patches to be mapped back to the original text lines reliably, because different lines were mapped to the same character, so the inverse process maps all such chars to the first mapped line.
It should be possible to scale correct diffing to much larger inputs by using a larger target space of symbols, such as by using 2 or 3 characters to represent unique lines.
I'm new at javascript and trying to do some loop that will automaticly will format a number (1000 = 1K , 10000 = 10k 100000 = 100k )
formatting to 1K works and then it stops for some reason...
for me this loop makes sense :
loop will cycle once so the condition will be true , this will give me the first 2 integers and a 'K', after that the loop will break
if condition is not true , loop should be continue...
this is probaly not the ideal way to do it , but i wondering why my logic thinking is wrong
thanks advanced and sorry for my bad english.
<body >
<p>Number: <span id="number"></span></p>
<script>
len=1;
thousand=1000;
million =1000000;
num= 10001;
for(thousand;thousand<million;thousand*=10){ //when thousand is less then a million , multiply thousand times 10
if(num>=thousand && num<(thousand*10)){ // should cycle the loop twice so i got num>=10000 && num<100000
document.getElementById("number").innerHTML = num.toString().substring(0,len)+" K";
len+=1; // increase by 1 , so i will get 10 K instead of 1 K
break; // should break now since condition is true after second cycle
}
}
// probaly not the ideal method to do this , i just want to know my problem because this loop makes sense to me....
</script>
</body>
A loop just makes no sense in this case, because you don't have an array type to iterate over.
Additionally generating a range to loop, like you are tyring to do isn't worth, since you could just
n = Math.floor(n / 1000) + 'k';
see chrisz answer for a working 'number to k' filter.
If you really want to loop. Try this:
let n = 3024;
for (let i = 0; i < 1000; i++) {
if (n >= i * 1000 && n < (i + 1) * 1000) {
console.log(i + 'k');
break;
}
}
I just completed some form of a competency exam for a programming school, and I got every question correct except this, although it appears really quite easy, yet I couldn't get it. Any ideas?
Observe the code below.
var x = [1,5,7,13];
for(i=0; i < x.length; i++)
{
x[i] = x[3-i] + 2;
}
Once the program is done, what would be in x?
a [3,7,9,15]
b [15,9,11,3]
c [15,9,7,3]
d [15,9,11,17]
The answer is d
first loop
x[0] = 13 + 2 = 15
second loop
x[1] = 7 + 2 = 9
third loop
x[2] = 9 + 2 = 11
fourth loop
x[3] = 15 + 2 = 17
x = {15, 9, 11, 17}
To figure this out, you'll have to understand that x[] is used to refer to a specific index of the array. For example:
var x = [5,6,7];
In this case, x[0] would be equal to 5, assuming a 0-index based array.
Knowing this, let's break down your loop. We'll start by filling in the variable name instead of the variable value step by step, to leave out confusion of following variables in your head.
var x = [1,5,7,13];
for(0=0; 0 < x.length; 0++)
{
x[0] = x[3-0] + 2;
}
For the first iteration, everything starts to become a little clearer as you can tell that now it's setting x[0] (the first value in the array) to equal x[3-0] (which would be x[3], which in turn would be 13 due to the 0-index array), plus 2. 13 + 2 = 15. The first number is 15.
var x = [1,5,7,13];
for(1=1; 1 < x.length; 1++)
{
x[1] = x[3-1] + 2;
}
Let's try one more! x[3-1] is the same as x[2] which is 7; 7 + 2 = 9. Your second number is 9.
Following the same logic you can see how the loop functions and understand how it's referencing the array's values.
The key here is that you're updating the same array you're reading from as you go through it. (Note: generally I'd consider this bad practice and I've seen a lot of programmers fall into this trap - it's very easy to misunderstand the code).
First thing to realize is that x[3-i] basically reads the opposite end of the current index. To be more generic, it should really have been x[(x.length-1)-i] but the 3 is hardcoded in this case.
Now, the first round is easy: 13+2 = 15. 13 because the opposite end of the first element is the last element:
x = [15,5,7,13]
▲ │ this+2
└──────┘
In the second round we replace 5 with 7+2 = 9:
x = [15,9,7,13]
▲ │ this+2
└─┘
In the third round we find ourselves doing something not initially obvious. Instead of replacing 7 with 5+2 we replace it with 9+2 instead because we've already replaced 5 with 9:
x = [15,9,11,13]
│ ▲
this+2 └─┘
Now finally we replace the last element with 15+2 using the same reasoning above:
x = [15,9,11,17]
│ ▲
└───────┘
this+2
I'm trying to get a recursive function to work in jQuery but I'm getting the following exception:
'Uncaught RangeError: Maximum call stack size exceeded'
My understanding is that the recursive function must somehow be running infinitely but I can't work out why that's happening. Thanks...
jQuery.fn.reduceNumber = function(numberToReduce) {
if (numberToReduce < 10 || numberToReduce == 11 || numberToReduce == 22 || numberToReduce == 33){
return numberToReduce;
} else {
var newNumberToReduce = numberToReduce.toString().substring(0,1) + numberToReduce.toString().substring(1,2);
return ($(this).reduceNumber(newNumberToReduce));
}
}
$(document).ready(function(){
$("#foo").html($(this).reduceNumber(12));
});
Because you are stuck in an infinite loop. You are calling reduceNumber(12). Since it does not match the first if() statement, it goes to the second:
var newNumberToReduce = numberToReduce.toString().substring(0,1) + numberToReduce.toString().substring(1,2);
Leading newNumberToReduce to be.... 12! Which then calls reduceNumber(12), which does the same thing again and again and again, until the maximum stack size is exceeded.
When you call reduceNumber the first time and pass 12
It goes to the function
It isn't smaller than 10, or equals to 11 or 22 or 33
So does the else
The newNumberToReduce is the first character of 12 (1) and second character of 12 (2)
So newNumberToReduce is 12
Calls the reduceNumber function again passing in 12 (again)
Therefore infinte loop
change this line:
var newNumberToReduce = numberToReduce.toString().substring(0,1) + numberToReduce.toString().substring(1,2);
to this:
var newNumberToReduce = (numberToReduce.toString().substring(0,1) | 0) + (numberToReduce.toString().substring(1,2) | 0);
that will create a new number combined from your digits (1 + 2 = 3)
I am having trouble getting this nested while loop to work. I am using a Javascript based program that reads from 2 table columns based on the Header of the table. I am able to read from the tables but the loop is not working. My goal is to find when the neutral size of a wire becomes larger than the phase size and print the wire size at which this occurs. The code is as follows.
CSA = 130
NeutCSA = 0
i = 0
j = 0
while (NeutCSA < CSA){
j = 0
while (NeutCSA < CSA){
NeutCSA = colWireSize[i] * colNumberWires[j]
if (colNumberWires[j] < 18){
j = j + 1
}
}
if (colWireSize[i] < 10){
i = i + 1
}
}
result = colNumberWires[j]
The tables look like this
colWireSize
2
3
4
5
6
7
8
9
10
colNumberWires
6
7
8
9
10
11
12
13
14
15
16
17
18
The program will find the condition and end the loop but not in the order I need it to. I need it to start at the first row of WireSizes and then loop through and multiple that value by NumberWires. If this value is less then CSA, go to the next WireSize and repeat the process until NeutCSA > CSA.
Thanks
Pat
Your outer loop does not loop as the inner loop will always advance NeutCSA to >= CSA.
Did you mean to set the exact same conditional for each loop?