understanding usage of eval() to evaluate boolean - javascript

I was just going through the code of timer.js HERE. and came across the following lines of code:
var paramList = ['autostart', 'time'];
for (var arg in paramList) {
if (func[paramList[arg]] != undefined) {
eval(paramList[arg] + " = func[paramList[arg]]");
}
};
In the source code its all on one line, but i've made it more readable above , my difficulty is with the usage of eval, I.E. the below line of code:
eval(paramList[arg] + " = func[paramList[arg]]");
now if i add a breakpoint in chrome to the above line and go to the console and paste the line of code i get the following:
true
How come ? lets have a close look at the statement again:
eval(paramList[arg] + " = func[paramList[arg]]");
what is the + doing here ? converting paramList[arg] to a string , in which case eval is being used as follows:
eval("paramList[arg] = func[paramList[arg]]");
?
or is the plus sign being used for concatenation purpose ? (which i think is very unlikely !)
I have read MDN eval(), but still had doubts.
can anybody explain the breakdown of that statement please ?
Thank you.

eval takes a string. What you have:
eval(paramList[arg] + " = func[paramList[arg]]");
The + is just string concatenation.
Is equivalent to:
var code = paramList[arg] + " = func[paramList[arg]]"
eval(code);
So I'd say it should be equivalent to:
global[paramList[arg]] = func[paramList[arg]];
Or, in this particular example (with var paramList = ['autostart', 'time'];)):
if (func['autostart'] != undefined)
autostart = func['autostart'];
if (func['time'] != undefined)
time = func['autostart'];

Related

How to setup position with FEN string in stockfish.js?

I want to make a chess puzzle on my website for my student.
I use stockfish.js to play with the engine.
How to change the start position on the board?
I try to change all FEN string but did not work.
Where to look for the function or something?
Anybody can help me, please?
Interacting with the javascript port of Stockfish is (at time of writing) still like communicating with a chess engine that uses/supports UCI (Universal Chess Interface).
The UCI position command should suffice:
var fenString = "rnbqkbnr/ppppp1pp/8/5p2/3P4/8/PPP1PPPP/RNBQKBNR w KQkq - 0 2"
// start UCI
stockfish.postMessage("uci");
// start new game
stockfish.postMessage("ucinewgame");
// set new game position
stockfish.postMessage("position fen " + fenString);
// start search
stockfish.postMessage("go depth 10");
Edited: Updated case for postMessage() function.
I was working on the same thing and figured it out -- it's by no means obvious and within the stockfish example there are lots of little trips and pitfalls. I found a couple questions online and thought I'd give them some answers.
So -- this answer assumes working with the example code found here: https://github.com/nmrugg/stockfish.js/tree/Stockfish11/example.
There are two major modifications that need to happen - first in the index.html file and second in enginegame.js.
First we'll define a helper function which will make it easy to work with the url "search" as it's called:
function searchToObject() {
var pairs = window.location.search.substring(1).split("&"),
obj = {},
pair,
i;
for ( i in pairs ) {
if ( pairs[i] === "" ) continue;
pair = pairs[i].split("=");
obj[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] );
}
return obj;
}
For ease I just placed that function in both files, within index.html it's at the beginning of the script tag, in enginegame.js it's the very first line. Also btw, I certainly pilfered that from stackoverflow, but I can't seem to find that answer any more, rats.
In index.html the newGame function wants to look like this:
newGame = function newGame() {
var baseTime = parseFloat($('#timeBase').val()) * 60;
var inc = parseFloat($('#timeInc').val());
var skill = parseInt($('#skillLevel').val());
game.reset();
let search = searchToObject();
if (search.player) {
game.setPlayerColor(search.player)
} else {
game.setPlayerColor($('#color-white').hasClass('active') ? 'white' : 'black');
}
if (search.fen) {
game.game.load(search.fen);
game.board.position(game.game.fen());
}
game.setTime(baseTime, inc);
game.setSkillLevel(skill);
game.setDisplayScore($('#showScore').is(':checked'));
game.start();
}
Note the game.game and game.board -- those need to be added in enginegame.js where it's returning an object. If I were writing this I would have done it differently, but I didn't have the patience to rename things.
Next up in enginegame.js we need to adjust prepareMove.
function prepareMove() {
stopClock();
$('#pgn').text(game.pgn());
board.position(game.fen());
updateClock();
var turn = game.turn() == 'w' ? 'white' : 'black';
if (!game.game_over()) {
if (turn != playerColor) {
let search = searchToObject();
if (search.fen) {
uciCmd('position fen ' + search.fen + ' moves ' + get_moves());
} else {
uciCmd('position startpos moves' + get_moves());
uciCmd('position startpos moves' + get_moves(), evaler);
}
evaluation_el.textContent = "";
uciCmd("eval", evaler);
if (time && time.wtime) {
uciCmd("go " + (time.depth ? "depth " + time.depth : "") + " wtime " + time.wtime + " winc " + time.winc + " btime " + time.btime + " binc " + time.binc);
} else {
uciCmd("go " + (time.depth ? "depth " + time.depth : ""));
}
isEngineRunning = true;
}
if (game.history().length >= 2 && !time.depth && !time.nodes) {
startClock();
}
}
}
See, the trick is that if ever there was a fen string to start the game, every subsequent position call needs to be different. I think that's probably what's tripping most people up - that's definitely what got me.
What helped things click for me was reading through the UCI documentation. Before that my board was in some crazy infinite loop.
Also one weird but critical bit I stumbled onto was the game.game.load(<fen string>) function call in the index.html file. I can't find any documentation for that. I don't even remember how I found it. But there it is!

In javascript, spliting a string with order preserving

hosts=".uk.com:hostname:#10.10.10.10/10:#[2001:db8:1/64]:#11.11.11.11/11:#[::2/24]"
In javascript, how do i split the above string("hosts") string like the following :
newhosts=.uk.com,hostname,#10.10.10.10/10,#[2001:db8:1/64],#11.11.11.11/11,#[::2/24]"
tried this :
var hosts, newhosts;
var ip6_hosts = [];
var ip6_re = /#\[(.*?)\]/g;
hosts=".uk.com:hostname:#10.10.10.10/10:#[2001:db8:1/64]:#11.11.11.11/11:#[::2/24]";
while ((match=ip6_re.exec(hosts)) != null)
ip6_hosts.push(match[0]);
non_ip6_hosts=hosts.replace(ip6_re, '').replace(/:+/g, ':');
newhosts=ip6_hosts.concat(non_ip6_hosts.split(':'));
actual output :
newhosts=#[2001:db8:1/64],#[::2/24],.uk.com,hostname,#10.10.10.10/10,#11.11.11.11/11
expected output :
newhosts=.uk.com,hostname,#10.10.10.10/10,#[2001:db8:1/64],#11.11.11.11/11,#[::2/24]
but not sure how to preserve the order. is there any way to achieve an expected output ?
You could try:
var openbracket=0;
for (i=0; i<hosts.length; i++)
{
if (hosts.substr(i,1) == '[') openbracket=openbracket+1;
if (hosts.substr(i,1) == ']') openbracket=openbracket-1;
if ((hosts.substr(i,1) == ':') && openbracket==0)
{
hosts = hosts.substr(0,i) + ',' + hosts.substr(i+1,hosts.length-i-1);
}
}
seems to work for me, though I'm not sure if there's a better method for changing the value of hosts. All it needs to do is insert the ',' at the location i. The above code adds everything to the left of the ':', a ',', and everything to the right of the ':'.
note: this assumes you don't want any ':' inside of brackets changed to a comma.
hope this helps.
Can't You just say:
host = host.replace(/:+/, ',');
whenever you want to change it?
I feel like this is too simple of an answer, comment if I'm not getting it.
The following should work:
hosts.replace(/([^:]{1})\:{1}([^:]{1})/g, '$1,$2')
Try this.
var hosts='.uk.com:hostname:#10.10.10.10/10:#[2001:db8:1/64]:#11.11.11.11/11:#[::2/24]';
hosts = hosts.replace(/:#/g, ':##');
hosts = hosts.split(':#');
var hostDetails = hosts[0].split(':');
var newHost = hostDetails.concat(hosts.splice(1, hosts.length));
console.log(newHost);
Can you try this...
String.prototype.replaceAt=function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
hosts=".uk.com:hostname:#10.10.10.10/10:#[2001:db8:1/64]:#11.11.11.11/11:#[::2/24]"
hosts = hosts.split(':#').join(',#');
var re = /:\w/g;
var found = hosts.match(re);
hosts.replaceAt(found.index,',');

jQuery if condition doesn't return expected result

I am confused why the if condition not producing the result
Return result of fxresult value = " Call for price " this is not code and just for reference of variable result.
var fxresult = $(".price").html();
var fxRate = fxresult.replace(/ /g,"");
if (fxRate == 'Callforprice'){
alert("found")
}
may you use this regexp instead of yours.
var fxRate = fxresult.replace(/\s/g,"");
yours will work to but i think this one is a lil bit better because you avoid typos like one whitespace or two.
and you have a typo here
var fxresult value = " Call for price "
//---------------------------------------^
missing a ;
but your major problem in this line is
var fxresult value = " Call for price "
//----------^
you have a problem with the var declaration (variable names can't contain spaces)
see working FIDDLE

Javascript - concat string does not work as expected

What's the wrong with this Javascript line?
user: h.reem
domain: somedomain
var target = "//account/win/winlogin.aspx" +
"?username=" +
user.toString() +
"&domain=" +
domain.toString();
the resutl is always:
//account/win/winlogin.aspx?username=h.reem
Any idea!!
alert(user + "X") shows only h.reem
The ActiveX component is probably returning a null terminated string (I've seen this with Scripting.TypeLib & a couple of the AD objects for example) so concatenating it with another string fails. (You can verify this if 0 === user.charCodeAt(user.length - 1)).
You will need remove the last character before using the string;
user = user.substr(0, user.length - 1);
try:
var sUser = user.toString();
var sDomain = domain.toString();
var target = "//account/win/winlogin.aspx" + "?username=" + sUser + "&domain=" + sDomain;
The above might not fix your problem but it should expose it - Could be that your user.toString() method isn't returning a string and is short-circuiting things... If this doesn't answer your question I'd be glad to assist further, but it would be helpful if you posted the implementation or source of "user" somewhere ...

Improve this search engine detecter with javascript

I have the following code which detects which search engine and what search term has been used:
if (document.referrer.search(/google\.*/i) != -1) {
var start = document.referrer.search(/q=/);
var searchTerms = document.referrer.substring(start + 2);
var end = searchTerms.search(/&/);
end = (end == -1) ? searchTerms.length : end;
searchTerms = searchTerms.substring(0, end);
if (searchTerms.length != 0) {
searchTerms = searchTerms.replace(/\+/g, " ");
searchTerms = unescape(searchTerms);
alert('You have searched: '+searchTerms+' on google');
}
}
That actually works, but unfortunately it doesn't work as expected sometimes.
Sometimes if the referrer was even not google i get an alert with the search term as : ttp://www.domain.com ( without H at the start ) i think that may lead to the bug.
Appreciate any help!
Have you tried leveraging existing JS URL parsing schemes? It might save you a bunch of time. For example:
http://blog.stevenlevithan.com/archives/parseuri
It's cutting the "h" off because q= was not in the referrer string. So your start variable is -1. Then you add 2 to that to get your searchTerms var with a substring. You need to check for start to be equal to -1 and return.
I also think your "google" string detection is not bulletproof, I would rather do something like this...
var ref = document.referrer;
var pcol = ref.indexOf("://") + 3;
if(ref.indexOf("google.com") == pcol || ref.indexOf("www.google.com") == pcol) {
// It is google
}
One last thing, you should use decodeURIComponent instead of unescape.

Categories