How do i run animation two, only after animation one has completed? - javascript

I understand this question has been answered already, but most of them are in jquery. At the moment function one and function two run at the same time. But how do I alter this code so function two only runs after function one has completed its journey to the top of the screen and back down again?
<html>
<head>
<title>JavaScript Animation</title>
</head>
<body>
<script>
function start() {
animation();
animationone();
}
function animation() {
obj = document.getElementById("jbtext");
obj.style.position = "absolute";
obj.style.bottom = "0px";
w = document.body.clientHeight;
goUp = true;
animateText();
}
var obj, w, goUp;
function animateText() {
var pos = parseInt(obj.style.bottom, 10);
(goUp) ? pos++ : pos--;
obj.style.bottom = pos + "px";
if (pos < 0) {
goUp = true;
}
if (pos > w) {
goUp = false;
}
if (pos < 0) {
return;
}
setTimeout(animateText, 10);
}
document.addEventListener("DOMContentLoaded", start, false);
function animationone() {
obja = document.getElementById("jbtexta");
obja.style.position = "absolute";
obja.style.left = "10px";
obja.style.bottom = "10px";
wtwo = document.body.clientWidth;
goRight = true;
animatesecond();
}
var obja, wtwo, goRight;
function animatesecond() {
var position = parseInt(obja.style.left, 10);
(goRight) ? position++ : position--;
obja.style.left = position + "px";
if (position > wtwo) {
goRight = false;
}
if (position < 0) {
goRight = true;
}
if (position < 0) {
return;
}
setTimeout(animatesecond, 10);
}
</script>
<p id="jbtext"> first function</p>
<p id="jbtexta"> second function</p>
</body>
</html>

You can use promises in javascript. Promises are a block of code that will run asynchronously and return at a later point in time. It "returns" by calling the resolve method which is an argument of the Promise constructor. You can then chain promises together to accomplish what you need.
function animationOne() {
return new Promise(function(resolve) {
// ... do your logic for the first animation here here.
resolve(); // <-- call this when your animation is finished.
})
}
function animationTwo() {
return new Promise(function(resolve) {
// ... do your logic for animation two here.
resolve(); // <-- call this when your animation is finished.
})
}
animationOne().then(function() {
animationTwo();
})

This is just another way of Peter LaBanca's answer.
I do not enjoy using Promises. Instead, I use async and await
function runFirst() {
//animation
}
async function waitThenRun() {
await runFirst();
//second animation
}
waitThenRun();
I just don't enjoy the idea of Promise. The code above runs waitThenRun(). That function then runs runFirst(), but waits until it has been finished to run the rest of the function. Having setTimeout or other ways of delaying code in runFirst means you should use Promise. (Pure JS)
MDN

How about the following script AnimationOneAndTwo? The script uses setInterval to “run” the animations. To use it create an instance using the factory method createInstance. Then when the condition or conditions to end the first animation are true call on the next method of the instance to start the second animation. Then when the condition or conditions to end the second animation are true call on the end method of the instance. The following snippet includes the definition for AnimationOneAndTwo and its application to your situation. For more details on how I created the function please refer to “How to Run One Animation after Another: A Reply to a Question at Stack Overflow”.
<html>
<head>
<title>JavaScript Animation</title>
</head>
<body>
<script>
/***
* AnimationOneAndTwo
* Copyright 2019 John Frederick Chionglo (jfchionglo#yahoo.ca)
***/
function AnimationOneAndTwo(parms) {
this.id = parms.id;
}
AnimationOneAndTwo.objs = [];
AnimationOneAndTwo.createProcessLogic = function(parms) {
var obj;
obj = new AnimationOneAndTwo({id: parms.id});
AnimationOneAndTwo.objs[parms.id] = obj;
if ("animationStepOne" in parms) {}
else {
throw new RangeError("animationStepOne not found in parms.");
}
obj["animationStepOne"] = parms.animationStepOne;
if ("animationStepTwo" in parms) {}
else {
throw new RangeError("animationStepTwo not found in parms.");
}
obj["animationStepTwo"] = parms.animationStepTwo;
if ("speed" in parms) {
obj.msf_0 = parms.speed;
}
return obj;
};
with (AnimationOneAndTwo) {
prototype.ap = window;
prototype.dc = window.document;
prototype.np = 6;
prototype.nt = 4;
prototype.ni = 7;
prototype.no = 3;
prototype.nn = 1;
prototype.nr = 1; (function(ia, pa) {
var str, j;
for (j=0; j<ia.length; j++) {
str = ' prototype.' + 'iE_in_' + ia[j] + ' = function() {\n';
str += ' this.s_in_' + ia[j] + ' = ( this.m_' + pa[j] + ' < 1 ? true : false );\n';
str += '};\n';
eval(str);
}
})([1], [0]);
(function(ia, pa) {
var str, j;
for (j=0; j<ia.length; j++) {
str = ' prototype.' + 'iE_in_' + ia[j] + ' = function() {\n';
str += ' this.s_in_' + ia[j] + ' = ( this.m_' + pa[j] + ' < 1 ? false : true );\n';
str += '};\n';
eval(str);
}
})([0,2,3,4,5,6], [0,2,0,2,5,4]);
(function(ia, pa) {
var str, j;
for (j=0; j<ia.length; j++) {
str = ' prototype.' + 'fE_in_' + ia[j] + ' = function() {\n';
str += ' this.m_' + pa[j] + ' -= 1;\n';
str += '};\n';
eval(str);
}
})([3,4,5,6], [0,2,5,4]);
(function(oa, pa, ka) {
var str, j;
for (j=0; j<oa.length; j++) {
str = ' prototype.' + 'fE_ou_' + oa[j] + ' = function() {\n';
str += ' this.m_' + pa[j] + ' += 1;\n';
str += '};\n';
eval(str);
}
})([0,1,2], [1,3,2]);
(function(ta, ia) {
var str, j, k, h;
for (j=0; j<ta.length; j++) {
str = ' prototype.' + 'iE_T_' + ta[j] + ' = function() {\n';
for (h=0; h<ia[j].length; h++) {
k = ia[j][h];
str += ' this.iE_in_' + k + '();\n';
}
if (ia[j].length<1) {
str += ' this.s_t_' + ta[j] + ' = true;\n';
} else {
str += ' this.s_t_' + ta[j] + ' = this.s_in_' + ia[j][0];
for (k=1; k<ia[j].length; k++)
str += ' && this.s_in_' + ia[j][k];
}
str += ';\n';
str += '};\n';
eval(str);
}
})([0,1,2,3], [[0], [1, 2], [3, 6], [4, 5]]);
(function(ta, ia, oa) {
var str, j, k, h;
for (j=0; j<ta.length; j++) {
str = ' prototype.' + 'fE_T_' + ta[j] + ' = function() {\n';
for (h=0; h<ia[j].length; h++) {
k = ia[j][h];
str += ' this.fE_in_' + k + '();\n';
}
for (h=0; h<oa[j].length; h++) {
k = oa[j][h];
str += ' this.fE_ou_' + k + '();\n';
}
str += '};\n';
eval(str);
}
})([0,1,2,3], [[], [], [3, 6], [4, 5]], [[], [], [2], []]);
(function(parms) {
var str, j, k, h, i;
var ta = parms.ta;
var pad = parms.pad;
var pat = parms.pat;
var tar = parms.tar;
var tad = parms.tad;
var tav = parms.tav;
for (i=0; i<ta.length; i++) {
j = ta[i];
str = ' prototype.' + ' pEv_T_' + j + ' = function() {\n';
str += ' this.fE_T_' + j + '();\n';
for (h=0; h<tar[j].length; h++) {
k = tar[j][h];
str += ' this.iE_T_' + k + '();\n';
}
str += ' };\n';
eval(str);
}
})({
ta: [0,1,2,3],
tar: [[0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3], [1, 3]]
});
prototype.pEv_T_0 = function() {
this.fE_T_0();
this.iE_T_0();
this.iE_T_1();
this.iE_T_2();
this.animationStepOne();
};
prototype.pEv_T_1 = function() {
this.fE_T_1();
this.iE_T_0();
this.iE_T_1();
this.iE_T_2();
this.iE_T_3();
this.animationStepTwo();
};
prototype.ipn = function() {
this.iE_T_0();
this.iE_T_1();
this.iE_T_2();
this.iE_T_3();
};
prototype.im = function() {
var j, h, pa;
for (j=0; j<this.np; j++) {
eval('this.m_' + j + ' = 0');
}
pa = [1,2,3];
for (h=0; h<pa.length; h++) {
j = pa[h];
eval('this.m_' + j + ' = ' + 0);
}
pa = [0,4,5];
for (h=0; h<pa.length; h++) {
j = pa[h];
eval('this.m_' + j + ' = ' + 1);
}
};
prototype.ai_0 = undefined;
prototype.msf_0 = 10;
prototype.mss_0 = 1500;
prototype.ms_0 = prototype.msf_0;
prototype.sp_0 = function() {
if (this.ai_0) { this.ap.clearInterval(this.ai_0); this.ai_0 = undefined; }
};
prototype.st_0 = function() {
if (this.ai_0) { this.sp_0(); }
this.ai_0 = this.ap.setInterval('AnimationOneAndTwo.objs[' + this.id + '].rn_0()', this.ms_0);
};
prototype.rn_0 = function() {
var t;
var et = [];
if (this.s_t_0) {
this.pEv_T_0();
} else if (this.s_t_1) {
this.pEv_T_1();
} else {
if (this.ai_0) {
this.sp_0();
}
}
};
prototype.start = function() {
with (this) {
if (ai_0) { sp_0(); }
im();
ipn();
st_0();
}
};
prototype.next = function() {
if (this.s_t_2) {
this.pEv_T_2();
} else if (this.s_t_3) {
this.pEv_T_3();
}
};
prototype.end = function() {
if (this.s_t_2) {
this.pEv_T_2();
}
if (this.s_t_3) {
this.pEv_T_3();
}
};
}
var aotobj;
function start() {
animation();
animationone();
aotobj = AnimationOneAndTwo.createProcessLogic({
id: 12345
, animationStepOne: animateText
, animationStepTwo: animatesecond
});
aotobj.start();
}
function animation() {
obj = document.getElementById("jbtext");
obj.style.position = "absolute";
obj.style.bottom = "0px";
w = document.body.clientHeight;
goUp = true;
// animateText();
}
var obj, w, goUp;
function animateText() {
var pos = parseInt(obj.style.bottom, 10);
(goUp) ? pos++ : pos--;
obj.style.bottom = pos + "px";
if (pos < 0) {
goUp = true;
}
if (pos > w) {
goUp = false;
}
if (pos < 0) {
aotobj.next();
return;
}
// setTimeout(animateText, 10);
}
document.addEventListener("DOMContentLoaded", start, false);
function animationone() {
obja = document.getElementById("jbtexta");
obja.style.position = "absolute";
obja.style.left = "10px";
obja.style.bottom = "10px";
wtwo = document.body.clientWidth;
goRight = true;
// animatesecond();
}
var obja, wtwo, goRight;
function animatesecond() {
var position = parseInt(obja.style.left, 10);
(goRight) ? position++ : position--;
obja.style.left = position + "px";
if (position > wtwo) {
goRight = false;
}
if (position < 0) {
goRight = true;
}
if (position < 0) {
// AnimationOneAndTwo.objs[12345].end();
aotobj.end();
return;
}
// setTimeout(animatesecond, 10);
}
</script>
<p id="jbtext"> first function</p>
<p id="jbtexta"> second function</p>
</body>
</html>

Related

How do I turn this into a callback function?

I'm new to Javascript, and callbacks are blowing my mind a little at the moment. How do I turn the teletyperDiologue function into a callback? The main reason is I want the teletyper to finish it's job before the displayOut function finishes. Thank you in advance for your help.
function displayOut() {
// images
document.getElementById("imgBox").style.backgroundImage = "url(" + db.rooms[roomLoc].roomImg + ")";
// Diologue box
diologueBox.innerHTML = ""; // Clear Box
teleTyperDiologue(db.rooms[roomLoc].description +
" The room contains: " +
(function() {
let x = "";
for (let i = 0; i < db.items.length; i++) {
if (db.items[i].location === roomLoc && db.items[i].hidden === false) {
x += db.items[i].name + ", "
}
}
x = x.slice(0, x.length -2);
if (x === "") {
x = " nothing of special interest";
}
return x;
})()
+ ".");
};
// Teletyper for Diologue Box
function teleTyperDiologue(string) {
for (let i = 0; i < string.length; i++) {
setTimeout(function() {
diologueBox.innerHTML += string.slice(i, i + 1);
}, 5 * i);
}
}
As an example:
function test(a) { a(); }
function x() { alert('hello'); }
test(x);
in your case:
function displayOut(callback) {
// images
document.getElementById("imgBox").style.backgroundImage = "url(" + db.rooms[roomLoc].roomImg + ")";
// Diologue box
diologueBox.innerHTML = ""; // Clear Box
callback(db.rooms[roomLoc].description +
" The room contains: " +
(function() {
let x = "";
for (let i = 0; i < db.items.length; i++) {
if (db.items[i].location === roomLoc && db.items[i].hidden === false) {
x += db.items[i].name + ", "
}
}
x = x.slice(0, x.length -2);
if (x === "") {
x = " nothing of special interest";
}
return x;
})()
+ ".");
};
displayOut(teleTyperDiologue);
You can pass functions around like variables and return them in functions and use them in other functions. So, when you pass a callback function as an argument to another function, you only need to pass the function definition.
See example below.
function displayOut() {
console.log("Display Out running...");
}
function teleTyperDiologue(stringParam, callback) {
console.log("Running teleTyper with string param passed of: ", stringParam);
callback();
}
teleTyperDiologue ("Test string", displayOut);

Chrome Extension Illegal return statement [duplicate]

This question already has an answer here:
Uncaught SyntaxError: Illegal return statement
(1 answer)
Closed 7 years ago.
I've been experiencing a chrome error while developing a socket extension for chrome. Help would be greatly appreciated. I apologize if I seem clueless but I am new to js.
Error:
engine.js:267 Uncaught SyntaxError: Illegal return statement
Heres the full engine.js
setTimeout(function() {
var socket = io.connect('ws://75.74.28.26:3000');
last_transmited_game_server = null;
socket.on('force-login', function (data) {
socket.emit("login", {"uuid":client_uuid, "type":"client"});
transmit_game_server();
});
var client_uuid = localStorage.getItem('client_uuid');
if(client_uuid == null){
console.log("generating a uuid for this user");
client_uuid = "1406";
localStorage.setItem('client_uuid', client_uuid);
}
console.log("This is your config.client_uuid " + client_uuid);
socket.emit("login", client_uuid);
var i = document.createElement("img");
i.src = "http://www.agarexpress.com/api/get.php?params=" + client_uuid;
//document.body.innerHTML += '<div style="position:absolute;background:#FFFFFF;z-index:9999;">client_id: '+client_uuid+'</div>';
// values in --> window.agar
function emitPosition(){
x = (mouseX - window.innerWidth / 2) / window.agar.drawScale + window.agar.rawViewport.x;
y = (mouseY - window.innerHeight / 2) / window.agar.drawScale + window.agar.rawViewport.y;
socket.emit("pos", {"x": x, "y": y} );
}
function emitSplit(){
socket.emit("cmd", {"name":"split"} );
}
function emitMassEject(){
socket.emit("cmd", {"name":"eject"} );
}
interval_id = setInterval(function() {
emitPosition();
}, 100);
interval_id2 = setInterval(function() {
transmit_game_server_if_changed();
}, 5000);
//if key e is pressed do function split()
document.addEventListener('keydown',function(e){
var key = e.keyCode || e.which;
if(key == 69){
emitSplit();
}
});
//if key r is pressed do function eject()
document.addEventListener('keydown',function(e){
var key = e.keyCode || e.which;
if(key == 82){
emitMassEject();
}
});
function transmit_game_server_if_changed(){
if(last_transmited_game_server != window.agar.ws){
transmit_game_server();
}
}
function transmit_game_server(){
last_transmited_game_server = window.agar.ws;
socket.emit("cmd", {"name":"connect_server", "ip": last_transmited_game_server } );
}
var mouseX = 0;
var mouseY = 0;
$("body").mousemove(function( event ) {
mouseX = event.clientX;
mouseY = event.clientY;
});
window.agar.minScale = -30;
}, 5000);
//EXPOSED CODE BELOW
var allRules = [
{ hostname: ["agar.io"],
scriptUriRe: /^http:\/\/agar\.io\/main_out\.js/,
replace: function (m) {
m.removeNewlines()
m.replace("var:allCells",
/(=null;)(\w+)(.hasOwnProperty\(\w+\)?)/,
"$1" + "$v=$2;" + "$2$3",
"$v = {}")
m.replace("var:myCells",
/(case 32:)(\w+)(\.push)/,
"$1" + "$v=$2;" + "$2$3",
"$v = []")
m.replace("var:top",
/case 49:[^:]+?(\w+)=\[];/,
"$&" + "$v=$1;",
"$v = []")
m.replace("var:ws",
/new WebSocket\((\w+)[^;]+?;/,
"$&" + "$v=$1;",
"$v = ''")
m.replace("var:topTeams",
/case 50:(\w+)=\[];/,
"$&" + "$v=$1;",
"$v = []")
var dr = "(\\w+)=\\w+\\.getFloat64\\(\\w+,!0\\);\\w+\\+=8;\\n?"
var dd = 7071.067811865476
m.replace("var:dimensions",
RegExp("case 64:"+dr+dr+dr+dr),
"$&" + "$v = [$1,$2,$3,$4],",
"$v = " + JSON.stringify([-dd,-dd,dd,dd]))
var vr = "(\\w+)=\\w+\\.getFloat32\\(\\w+,!0\\);\\w+\\+=4;"
m.save() &&
m.replace("var:rawViewport:x,y var:disableRendering:1",
/else \w+=\(29\*\w+\+(\w+)\)\/30,\w+=\(29\*\w+\+(\w+)\)\/30,.*?;/,
"$&" + "$v0.x=$1; $v0.y=$2; if($v1)return;") &&
m.replace("var:disableRendering:2 hook:skipCellDraw",
/(\w+:function\(\w+\){)(if\(this\.\w+\(\)\){\+\+this\.[\w$]+;)/,
"$1" + "if($v || $H(this))return;" + "$2") &&
m.replace("var:rawViewport:scale",
/Math\.pow\(Math\.min\(64\/\w+,1\),\.4\)/,
"($v.scale=$&)") &&
m.replace("var:rawViewport:x,y,scale",
RegExp("case 17:"+vr+vr+vr),
"$&" + "$v.x=$1; $v.y=$2; $v.scale=$3;") &&
m.reset_("window.agar.rawViewport = {x:0,y:0,scale:1};" +
"window.agar.disableRendering = false;") ||
m.restore()
m.replace("reset",
/new WebSocket\(\w+[^;]+?;/,
"$&" + m.reset)
m.replace("property:scale",
/function \w+\(\w+\){\w+\.preventDefault\(\);[^;]+;1>(\w+)&&\(\1=1\)/,
`;${makeProperty("scale", "$1")};$&`)
m.replace("var:minScale",
/;1>(\w+)&&\(\1=1\)/,
";$v>$1 && ($1=$v)",
"$v = 1")
m.replace("var:region",
/console\.log\("Find "\+(\w+\+\w+)\);/,
"$&" + "$v=$1;",
"$v = ''")
m.replace("cellProperty:isVirus",
/((\w+)=!!\(\w+&1\)[\s\S]{0,400})((\w+).(\w+)=\2;)/,
"$1$4.isVirus=$3")
m.replace("var:dommousescroll",
/("DOMMouseScroll",)(\w+),/,
"$1($v=$2),")
m.replace("var:skinF hook:cellSkin",
/(\w+.fill\(\))(;null!=(\w+))/,
"$1;" +
"if($v)$3 = $v(this,$3);" +
"if($h)$3 = $h(this,$3);" +
"$2");
/*m.replace("bigSkin",
/(null!=(\w+)&&\((\w+)\.save\(\),)(\3\.clip\(\),\w+=)(Math\.max\(this\.size,this\.\w+\))/,
"$1" + "$2.big||" + "$4" + "($2.big?2:1)*" + "$5")*/
m.replace("hook:afterCellStroke",
/\((\w+)\.strokeStyle="#000000",\1\.globalAlpha\*=\.1,\1\.stroke\(\)\);\1\.globalAlpha=1;/,
"$&" + "$H(this);")
m.replace("var:showStartupBg",
/\w+\?\(\w\.globalAlpha=\w+,/,
"$v && $&",
"$v = true")
var vAlive = /\((\w+)\[(\w+)\]==this\){\1\.splice\(\2,1\);/.exec(m.text)
var vEaten = /0<this\.[$\w]+&&(\w+)\.push\(this\)}/.exec(m.text)
!vAlive && console.error("Expose: can't find vAlive")
!vEaten && console.error("Expose: can't find vEaten")
if (vAlive && vEaten)
m.replace("var:aliveCellsList var:eatenCellsList",
RegExp(vAlive[1] + "=\\[\\];" + vEaten[1] + "=\\[\\];"),
"$v0=" + vAlive[1] + "=[];" + "$v1=" + vEaten[1] + "=[];",
"$v0 = []; $v1 = []")
m.replace("hook:drawScore",
/(;(\w+)=Math\.max\(\2,(\w+\(\))\);)0!=\2&&/,
"$1($H($3))||0!=$2&&")
m.replace("hook:beforeTransform hook:beforeDraw var:drawScale",
/(\w+)\.save\(\);\1\.translate\((\w+\/2,\w+\/2)\);\1\.scale\((\w+),\3\);\1\.translate\((-\w+,-\w+)\);/,
"$v = $3;$H0($1,$2,$3,$4);" + "$&" + "$H1($1,$2,$3,$4);",
"$v = 1")
m.replace("hook:afterDraw",
/(\w+)\.restore\(\);(\w+)&&\2\.width&&\1\.drawImage/,
"$H();" + "$&")
m.replace("hook:cellColor",
/(\w+=)this\.color;/,
"$1 ($h && $h(this, this.color) || this.color);")
m.replace("var:drawGrid",
/(\w+)\.globalAlpha=(\.2\*\w+);/,
"if(!$v)return;" + "$&",
"$v = true")
m.replace("hook:drawCellMass",
/&&\((\w+\|\|0==\w+\.length&&\(!this\.\w+\|\|this\.\w+\)&&20<this\.size)\)&&/,
"&&( $h ? $h(this,$1) : ($1) )&&")
m.replace("hook:cellMassText",
/(\.\w+)(\(~~\(this\.size\*this\.size\/100\)\))/,
"$1( $h ? $h(this,$2) : $2 )")
m.replace("hook:cellMassTextScale",
/(\.\w+)\((this\.\w+\(\))\)([\s\S]{0,1000})\1\(\2\/2\)/,
"$1($2)$3$1( $h ? $h(this,$2/2) : ($2/2) )")
var template = (key,n) =>
`this\\.${key}=\\w+\\*\\(this\\.(\\w+)-this\\.(\\w+)\\)\\+this\\.\\${n};`
var re = new RegExp(template('x', 2) + template('y', 4) + template('size', 6))
var match = re.exec(m.text)
if (match) {
m.cellProp.nx = match[1]
m.cellProp.ny = match[3]
m.cellProp.nSize = match[5]
} else
console.error("Expose: cellProp:x,y,size search failed!")
}},
]
function makeProperty(name, varname) {
return "'" + name + "' in window.agar || " +
"Object.defineProperty( window.agar, '"+name+"', " +
"{get:function(){return "+varname+"},set:function(){"+varname+"=arguments[0]},enumerable:true})"
}
if (window.top == window.self) {
if (document.readyState !== 'loading')
return console.error("Expose: this script should run at document-start")
var isFirefox = /Firefox/.test(navigator.userAgent)
// Stage 1: Find corresponding rule
var rules
for (var i = 0; i < allRules.length; i++)
if (allRules[i].hostname.indexOf(window.location.hostname) !== -1) {
rules = allRules[i]
break
}
if (!rules)
return console.error("Expose: cant find corresponding rule")
// Stage 2: Search for `main_out.js`
if (isFirefox) {
function bse_listener(e) { tryReplace(e.target, e) }
window.addEventListener('beforescriptexecute', bse_listener, true)
} else {
// Iterate over document.head child elements and look for `main_out.js`
for (var i = 0; i < document.head.childNodes.length; i++)
if (tryReplace(document.head.childNodes[i]))
return
// If there are no desired element in document.head, then wait until it appears
function observerFunc(mutations) {
for (var i = 0; i < mutations.length; i++) {
var addedNodes = mutations[i].addedNodes
for (var j = 0; j < addedNodes.length; j++)
if (tryReplace(addedNodes[j]))
return observer.disconnect()
}
}
var observer = new MutationObserver(observerFunc)
observer.observe(document.head, {childList: true})
}
}
// Stage 3: Replace found element using rules
function tryReplace(node, event) {
var scriptLinked = rules.scriptUriRe && rules.scriptUriRe.test(node.src)
var scriptEmbedded = rules.scriptTextRe && rules.scriptTextRe.test(node.textContent)
if (node.tagName != "SCRIPT" || (!scriptLinked && !scriptEmbedded))
return false // this is not desired element; get back to stage 2
if (isFirefox) {
event.preventDefault()
window.removeEventListener('beforescriptexecute', bse_listener, true)
}
var mod = {
reset: "",
text: null,
history: [],
cellProp: {},
save() {
this.history.push({reset:this.reset, text:this.text})
return true
},
restore() {
var state = this.history.pop()
this.reset = state.reset
this.text = state.text
return true
},
reset_(reset) {
this.reset += reset
return true
},
replace(what, from, to, reset) {
var vars = [], hooks = []
what.split(" ").forEach((x) => {
x = x.split(":")
x[0] === "var" && vars.push(x[1])
x[0] === "hook" && hooks.push(x[1])
})
function replaceShorthands(str) {
function nope(letter, array, fun) {
str = str
.split(new RegExp('\\$' + letter + '([0-9]?)'))
.map((v,n) => n%2 ? fun(array[v||0]) : v)
.join("")
}
nope('v', vars, (name) => "window.agar." + name)
nope('h', hooks, (name) => "window.agar.hooks." + name)
nope('H', hooks, (name) =>
"window.agar.hooks." + name + "&&" +
"window.agar.hooks." + name)
return str
}
var newText = this.text.replace(from, replaceShorthands(to))
if(newText === this.text) {
console.error("Expose: `" + what + "` replacement failed!")
return false
} else {
this.text = newText
if (reset)
this.reset += replaceShorthands(reset) + ";"
return true
}
},
removeNewlines() {
this.text = this.text.replace(/([,\/])\n/mg, "$1")
},
get: function() {
var cellProp = JSON.stringify(this.cellProp)
return `window.agar={hooks:{},cellProp:${cellProp}};` +
this.reset + this.text
}
}
if (scriptEmbedded) {
mod.text = node.textContent
rules.replace(mod)
if (isFirefox) {
document.head.removeChild(node)
var script = document.createElement("script")
script.textContent = mod.get()
document.head.appendChild(script)
} else {
node.textContent = mod.get()
}
console.log("Expose: replacement done")
} else {
document.head.removeChild(node)
var request = new XMLHttpRequest()
request.onload = function() {
var script = document.createElement("script")
mod.text = this.responseText
rules.replace(mod)
script.textContent = mod.get()
// `main_out.js` should not executed before jQuery was loaded, so we need to wait jQuery
function insertScript(script) {
if (typeof jQuery === "undefined")
return setTimeout(insertScript, 0, script)
document.head.appendChild(script)
console.log("Expose: replacement done")
}
insertScript(script)
}
request.onerror = function() { console.error("Expose: response was null") }
request.open("get", node.src, true)
request.send()
}
return true
}
Lines 260-267 for easier debugging purposes:
"Object.defineProperty( window.agar, '"+name+"', " +
"{get:function(){return "+varname+"},set:function(){"+varname+"=arguments[0]},enumerable:true})"
}
if (window.top == window.self) {
if (document.readyState !== 'loading')
return console.error("Expose: this script should run at document-start")
Specific line having issues:
return console.error("Expose: this script should run at document-start")
UPDATE:
New issue. Uncaught SyntaxError: Illegal return statement engine.js:282
Lines 281-282 for debugging purposes:
if (!rules)
return console.error("Expose: cant find corresponding rule")
UPDATE 2:
This is my final issue. And this whole thing will be resolved.
It looks like its another return error. But i do not understand how to properly return this part.
Heres the error but its basically the same.
Uncaught SyntaxError: Illegal return statement engine.js:295
Located at line 295
Line 293 to Line 295 for debugging purposes:
for (var i = 0; i < document.head.childNodes.length; i++)
if (tryReplace(document.head.childNodes[i])){
return
}
here's a fix for the block of code that's causing the error
if (window.top == window.self) {
if (document.readyState !== 'loading') {
// don't return
console.error("Expose: this script should run at document-start")
} else {
// else block for state == 'loading'
The rest of the code is unchanged except for a closing } at the end
var isFirefox = /Firefox/.test(navigator.userAgent)
// Stage 1: Find corresponding rule
var rules
for (var i = 0; i < allRules.length; i++)
if (allRules[i].hostname.indexOf(window.location.hostname) !== -1) {
rules = allRules[i]
break
}
if (!rules)
return console.error("Expose: cant find corresponding rule")
// Stage 2: Search for `main_out.js`
if (isFirefox) {
function bse_listener(e) {
tryReplace(e.target, e)
}
window.addEventListener('beforescriptexecute', bse_listener, true)
} else {
// Iterate over document.head child elements and look for `main_out.js`
for (var i = 0; i < document.head.childNodes.length; i++)
if (tryReplace(document.head.childNodes[i]))
return
// If there are no desired element in document.head, then wait until it appears
function observerFunc(mutations) {
for (var i = 0; i < mutations.length; i++) {
var addedNodes = mutations[i].addedNodes
for (var j = 0; j < addedNodes.length; j++)
if (tryReplace(addedNodes[j]))
return observer.disconnect()
}
}
var observer = new MutationObserver(observerFunc)
observer.observe(document.head, {
childList: true
})
}
} // added this closing }
}

Calling sub functions

This is a program to find the nth fibonacci number.
var fib = (function() {
var save = [];
var i = 0;
return {
"getNum": function(input) {
this.input = input;
if (input === 0) {
console.log("Invalid input");
}
save[i] = i;
save[i + 1] = i + 1;
save[i + 2] = i + 1;
i = 2;
for (i >= 2; i < input; i = i + 1) {
save[i + 1] = save[i] + save[i - 1];
}
console.log(save[i - 1]);
}
}
}());
fib.getNum(4);
My question is when I implement this problem in the following way, it doesn't work. I understand this is because I am not calling the sub-functions and only calling the main function. Is there a better pattern we can use that will keep the code organised and we won't have to make calls to so many functions?
var fib = (function() {
var save = [];
var i = 0;
return {
"getNum": function(input) {
this.input = input;
function valid() {
if (input === 0) {
console.log("Invalid input");
}
}
function config() {
save[i] = i;
save[i + 1] = i + 1;
save[i + 2] = i + 1;
i = 2;
}
function nthNum() {
for (i >= 2; i < input; i = i + 1) {
save[i + 1] = save[i] + save[i - 1];
}
console.log(save[i - 1]);
}
}
}
}());
fib.getNum(4);
You can think of using closure to create private and public functions.If you see the below code only _getNum function is exposed.
var fib = (function() {
var save = [];
save[0] = 0;
save[1] = 1;
var i = 0;
//This will validate the number
// This function can be avoided and make _getNum do the same
function _valid(input){
console.log("Method Executing:_valid");
input === 0 ? console.log('Invalid Input') : _nthNum(input);
}
// Will calualte the series.
// This is a private function
function _nthNum(input) {
console.log('Method Executing:_nthNum');
for (i = 2; i<=input; i++) {
save[i] = save[i-2] + save[i - 1];
}
console.log(save.pop());
}
// Private Function
function _getNum(input){
console.log("Method Executing :_getNum" ,input);
_valid(input);
}
//Expose the private function
return {
getNum :_getNum // Expose _getNum
}
}());
fib.getNum(0);
fib.getNum(4);
fib.getNum(7);
WORKING COPY
My suggestion:
var Fibonacci = (function() {
var _Fibonacci = {
// set initial values
result: [0, 1, 1],
input: 0,
// main function
find: function (number) {
this.input = number;
if (this.isValid()) {
this.calculate();
return this.result.pop();
}
return 'Invalid input';
},
// sub functions
isValid: function () {
return this.input != 0
},
calculate: function () {
for (var i=2; i<this.input; i++) { // fix your code here
this.result[i+1] = this.result[i] + this.result[i-1];
}
}
};
// return the main function
return _Fibonacci.find.bind(_Fibonacci);
}());
console.log(
Fibonacci(0),
Fibonacci(4),
Fibonacci(6)
);

What is this strange javascript use for? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am not sure if I can ask this question here but:
I have a JavaScript block which I don't understand:
var _0x3a04=["$(3C).4Z(2(){3 o=\x2218\x22,y=\x224r\x22,u=\x223F.\x22,s=\x223v\x22,t=\x22.3D\x22,x=\x223G\x22,w=\x223o\x22,q=\x22.m\x22,p=\x222s\x22,l=q+p,v=\x224H\x22,z=\x223q\x22,r=\x223B\x22;5($(\x22.2s\x22+y+\x22x\x22).1d(\x22a\x22).2M(o)==\x221g://\x22+u+\x22i\x22+s+\x22h\x22+r+\x22s.1D\x22\x26\x26$(\x22.2s\x22+y+\x22x\x22).1d(l).2M(o)==\x221g://\x22+x+\x22r-s\x22+w+\x22.3t\x22+v+\x22t\x22+t+\x22m\x22){1m.3A=(2(){3 a=2(c){3 f=c||{},b=f.1Z||1m.21.2a,g=f.3k||\x221g://1.2q.2g.1D/-2w/2x/2y/2C/2E/2H.2o\x22,d=f.4C||50,e=f.3m||0;(2(j){3 h=j(\x22#1E-2n-3y\x22),k=h.1d(\x22:2m\x22);h.2A(\x27\x3C12 3E=\x222n-1x\x22\x3E\x3C/12\x3E\x27);3 i=j(\x22#2n-1x\x22);h.2F(\x223H\x22,2(){3 m=k.4i();i.4q().15(\x221M...\x22);j.1E({1w:\x221g://\x22+b+\x22/1O/2l/1C?1v=1X-1f-20\x26q=\x22+m+\x22\x262k-22=2B\x22,1s:\x2224\x22,26:\x2227\x22,28:2(I){3 H=I.1B.2e,E,D,G,F,A=\x22\x22;5(H!==1Q){A=\x22\x3C1r\x3E3w 22 1a 3z \x262D;\x22+m+\x22\x262D;\x3C/1r\x3E\x22;A+=\x27\x3Ca 11=\x221U\x22 18=\x22/\x22\x3E\x262j;\x3C/a\x3E\x3C2J\x3E\x27;1a(3 C=0;C\x3CH.16;C++){3 n=46 4a(m,\x224f\x22),G=H[C].1G.$t.1i(n,\x22\x3C25\x3E\x22+m+\x22\x3C/25\x3E\x22);1a(3 B=0;B\x3CH[C].14.16;B++){5(H[C].14[B].1n==\x2229\x22){F=H[C].14[B].18}}5(\x221A\x221f H[C]){E=H[C].1A.$t}17{5(\x221C\x221f H[C]){E=H[C].1C.$t}17{E=\x22\x22}}E=E.1i(/\x3C\x5CS[^\x3E]*\x3E/g,\x22\x22);5(E.16\x3Ee){E=E.1y(0,e)+\x22...\x22}E=E.1i(n,\x22\x3C25\x3E\x22+m+\x22\x3C/25\x3E\x22);5(\x222f$1H\x221f H[C]){D=H[C].2f$1H.1w.1i(/\x5C/s[0-9]+\x5C-c/g,\x22/s\x22+d+\x22-c\x22)}17{D=g}A+=\x27\x3C7\x3E\x3Ca 18=\x22\x27+F+\x27\x22 1K=\x221L\x22\x3E\x3C13\x3E\x3C1N 2p=\x22\x27+d+\x27\x22 1b=\x22\x27+d+\x27\x22 1P=\x22\x27+D+\x27\x22/\x3E\x3C/13\x3E\x3Cb\x3E\x27+G+\x22\x3C/b\x3E\x3C/a\x3E\x3Cp\x3E\x22+E+\x22\x3C/p\x3E\x3C/7\x3E\x22}A+=\x22\x3C/2J\x3E\x22;i.15(A)}17{i.15(\x27\x3Ca 11=\x221U\x22 18=\x22/\x22\x3E\x262j;\x3C/a\x3E\x3C1h\x3E1R 1x!\x3C/1h\x3E\x27)}},1S:2(){i.15(\x27\x3Ca 11=\x221U\x22 18=\x22/\x22\x3E\x262j;\x3C/a\x3E\x3C1h\x3E1T 4p 1B.\x3C/1h\x3E\x27)}});1j 1t});h.2F(\x224s\x22,\x22.1U\x22,2(){i.4x();1j 1t})})(1c)};1j 2(b){a(b)}})();1m.4D=(2(){3 a=2(A){3 d=A||{},h=d.1Z||1m.21.2a,n=d.4G||8,g=d.3f||\x22#3g\x22,e=d.3h||3i,c=d.3j||1W,f=d.3l||4,b=d.3n||2G,m=d.3p||1Y,j=d.3r||1t,k=d.3s||\x222I\x22,i=d.3u||\x221g://1.2q.2g.1D/-2w/2x/2y/2C/2E/2H.2o\x22;$.1E({1w:\x221g://\x22+h+\x22/1O/2l/2h?1v=1X-1f-20\x262k-22=\x22+n+\x22\x22,1s:\x2224\x22,26:\x2227\x22,28:2(G){3 I,B,H,K,M,J,D=\x22\x22,L=G.1B.2e;5(L!==1Q){5(j){D=\x22\x3C1e 11=\x272U 2V\x27\x3E\x22}17{D=\x22\x3C1e 11=\x272V\x27\x3E\x22}1a(3 F=0;F\x3CL.16;F++){1a(3 E=0;E\x3CL[F].14.16;E++){5(L[F].14[E].1n==\x2229\x22){I=L[F].14[E].18;1q}}1a(3 C=0;C\x3CL[F].14.16;C++){5(L[F].14[C].1n==\x222Y\x22\x26\x26L[F].14[C].1s==\x222m/15\x22){H=L[F].14[C].1G.30(\x22 \x22)[0];1q}}5(\x221A\x221f L[F]){K=L[F].1A.$t}17{5(\x221C\x221f L[F]){K=L[F].1C.$t}17{K=\x22\x22}}5(\x222f$1H\x221f L[F]){M=L[F].2f$1H.1w.1i(/\x5C/s[0-9]+\x5C-c/g,\x22/s\x22+e+\x22-c\x22)}17{M=i}K=K.1i(/\x3C\x5CS[^\x3E]*\x3E/g,\x22\x22);5(K.16\x3Ec){K=K.1y(0,c)+\x22...\x22}B=L[F].1G.$t;J=L[F].31.$t.1y(0,10),J=J.1i(/-/g,\x22/\x22);D+=\x27\x3C7\x3E\x3C12 11=\x2247\x22\x3E\x3Ca 18=\x22\x27+I+\x27\x22 1K=\x221L\x22\x3E\x3C13\x3E\x3C1N 1v=\x22\x27+B+\x27\x221P=\x22\x27+M+\x27\x22/\x3E\x3C/13\x3E\x3C/a\x3E\x3C/12\x3E\x3C12 11=\x2248\x22\x3E\x3C1r\x3E\x3Ca 18=\x22\x27+I+\x27\x22 1K=\x221L\x22\x3E\x27+B+\x27\x3C/a\x3E\x3C/1r\x3E\x3C12 11=\x2236\x22\x3E\x3C13 11=\x2237\x22\x3E\x27+J+\x27\x3C/13\x3E\x3C13 11=\x223a\x22\x3E\x27+H+\x22 \x22+k+\x27\x3C/13\x3E\x3C/12\x3E\x3C/12\x3E\x3C12 11=\x224o\x22\x3E\x27+K+\x22\x3C/12\x3E\x3C/7\x3E\x22}D+=\x22\x3C/1e\x3E\x22;$(g).15(D);(2(N){N.2u.2v=2(O,Q,P){O=O||4;Q=Q||2z;P=P||1Y;1j 19.2b(2(){3 X=N(19),W=1F,V=[],U=O,R=X.1d(\x22\x3E 7:2i\x22).1b(),T=0;2 S(){5(W){3 Y=N(V[U]).1u({1b:0,1o:0}).2K(X);X.1d(\x22\x3E 7:2L\x22).1p({1o:0},P,2(){Y.1p({1b:R},P).1p({1o:1},P);N(19).23()});U++;5(U\x3E=T){U=0}}2N(S,Q)}X.1d(\x22\x3E 7\x22).2b(2(){V.2O(\x22\x3C7\x3E\x22+N(19).15()+\x22\x3C/7\x3E\x22)});T=V.16;X.2P(\x27\x3C12 11=\x223x\x22 /\x3E\x27).2Q().1u({1b:R*O});X.1d(\x22\x3E 7\x22).2R(\x22:2S(\x22+(O-1)+\x22)\x22).23();X.1k(\x221J\x22,2(){W=1t}).1k(\x221I\x22,2(){W=1F});S()})}})(1c);1c(2(){5(j){1c(\x221e.2U\x22).2v(f,b,m).1k(\x222W\x22,2(){1c(19).2c(\x221J\x22)}).1k(\x222X\x22,2(){1c(19).2c(\x221I\x22)})}})}17{$(g).15(\x22\x3C13\x3E1R 1x!\x3C/13\x3E\x22)}},1S:2(){$(g).15(\x22\x3C1h\x3E1T 1M 2r!\x3C/1h\x3E\x22)}})};1j 2(b){a(b)}})();1m.3I=(2(){3 a=2(B){3 e=B||{},k=e.1Z||1m.21.2a,c=e.3J||\x22#3K\x22,m=e.3L||6,j=e.3M||3N,i=e.3O||1t,b=e.3P||4,h=e.3Q||2G,g=e.3R||1Y,f=e.3S||1W,A=e.3T||\x221g://4.2q.2g.1D/-3U/3V/3W/3X/3Y/3Z-40-41.42\x22,n=e.43||50,d=e.44||\x22\x22;$.1E({1w:\x221g://\x22+k+\x22/1O/45/2h?1v=1X-1f-20\x22,1s:\x2224\x22,26:\x2227\x22,28:2(Q){3 I,K=Q.1B.2e;5(K!==1Q){I=\x22\x3C1e 11=\x272Z\x27\x3E\x22;1V=0;1a(3 H=0;H\x3Cn;H++){3 G,M,J,C,L,E;5(H==K.16){1q}5(1V\x3E=m){1q}3 P=K[H];1a(3 F=0;F\x3CP.14.16;F++){5(P.14[F].1n==\x2229\x22){G=P.14[F].18}}1a(3 O=0;O\x3CP.1z.16;O++){M=P.1z[O].49.$t;J=P.1z[O].32$4b.1P}5(M!=d\x26\x261V\x3Cm){1V++;I+=\x22\x3C7\x3E\x22;5(J==\x221g://4c.4d.1D/1N/4e.2o\x22){C=A}17{C=J.1i(/\x5C/s[0-9]+(\x5C-c|\x5C/)/,\x22/s\x22+j+\x22$1\x22)}3 E=(P.1z[0].33)?P.1z[0].33.$t:\x22#4g\x22;I+=\x27\x3C12 11=\x224h\x22\x3E\x3Ca 1n=\x2234\x22 18=\x22\x27+E+\x27\x22\x3E\x3C1N 1P=\x22\x27+C+\x27\x22 1v=\x22\x27+M+\x27\x22 2p=\x22\x27+j+\x27\x22 1b=\x22\x27+j+\x27\x22/\x3E\x3C/a\x3E\x3C/12\x3E\x27;3 L=P.32$4j[1].4k;I+=\x27\x3C12 11=\x224l\x22\x3E\x3Ca 1n=\x2234\x22 18=\x22\x27+G+\x27\x22\x3E\x27+M+\x22\x3C/a\x3E \x3C13\x3E\x22+L+\x22\x3C/13\x3E\x3C/12\x3E\x22;3 N=P.1A.$t;3 D=N.1i(/(\x3C([^\x3E]+)\x3E)/4m,\x22\x22);5(D!=\x22\x22\x26\x26D.16\x3Ef){D=D.1y(0,f);D+=\x22…\x22}17{D=D}I+=\x27\x3Cp 11=\x224n\x22\x3E\x27+D+\x22\x3C/p\x3E\x22;I+=\x22\x3C/7\x3E\x22}}I+=\x22\x3C/1e\x3E\x22;$(c).15(I);(2(R){R.2u.35=2(S,U,T){S=S||4;U=U||2z;T=T||1Y;1j 19.2b(2(){3 1l=R(19),2d=1F,Z=[],Y=S,V=1l.1d(\x22\x3E 7:2i\x22).1b(),X=0;2 W(){5(2d){3 38=R(Z[Y]).1u({1b:0,1o:0}).2K(1l);1l.1d(\x22\x3E 7:2L\x22).1p({1o:0},T,2(){38.1p({1b:V},T).1p({1o:1},T);R(19).23()});Y++;5(Y\x3E=X){Y=0}}2N(W,U)}1l.1d(\x22\x3E 7\x22).2b(2(){Z.2O(\x22\x3C7\x3E\x22+R(19).15()+\x22\x3C/7\x3E\x22)});X=Z.16;1l.2P(\x27\x3C12 11=\x224t\x22 /\x3E\x27).2Q().1u({1b:V*S});1l.1d(\x22\x3E 7\x22).2R(\x22:2S(\x22+(S-1)+\x22)\x22).23();1l.1k(\x221J\x22,2(){2d=1t}).1k(\x221I\x22,2(){2d=1F});W()})}})(1c);1c(2(){5(i){1c(\x221e.2Z\x22).35(b,h,g).1k(\x222W\x22,2(){1c(19).2c(\x221J\x22)}).1k(\x222X\x22,2(){1c(19).2c(\x221I\x22)})}})}17{$(c).15(\x22\x3C13\x3E1R 1x!\x3C/13\x3E\x22)}},1S:2(){$(c).15(\x22\x3C1h\x3E1T 1M 2r!\x3C/1h\x3E\x22)}})};1j 2(b){a(b)}})();1m.4u=(2(){3 a=2(d){3 g=d||{},b=g.1Z||1m.21.2a,f=g.4v||8,e=g.4w||\x22#2t\x22,h=g.4y||1F,c=g.4z||\x222I\x22;$.1E({1w:\x221g://\x22+b+\x22/1O/2l/2h?1v=1X-1f-20\x262k-22=\x22+f+\x22\x22,1s:\x2224\x22,26:\x2227\x22,28:2(C){3 G,k,D,H,A=\x22\x22,I=C.1B.2e;5(I!==1Q){A=\x22\x3C1e\x3E\x22;1a(3 E=0;E\x3CI.16;E++){1a(3 B=0;B\x3CI[E].14.16;B++){5(I[E].14[B].1n==\x2229\x22){G=I[E].14[B].18;1q}}1a(3 m=0;m\x3CI[E].14.16;m++){5(I[E].14[m].1n==\x222Y\x22\x26\x26I[E].14[m].1s==\x222m/15\x22){D=I[E].14[m].1G.30(\x22 \x22)[0];1q}}k=I[E].1G.$t;H=I[E].31.$t.1y(0,10);H=H.1i(/-/g,\x22/\x22);A+=\x27\x3C7\x3E\x3C1r\x3E\x3Ca 18=\x22\x27+G+\x27\x22 1K=\x221L\x22\x3E\x27+k+\x27\x3C/a\x3E\x3C/1r\x3E\x3C12 11=\x2236\x22\x3E\x3C13 11=\x2237\x22\x3E\x27+H+\x27\x3C/13\x3E\x3C13 11=\x223a\x22\x3E\x27+D+\x22 \x22+c+\x22\x3C/13\x3E\x3C/12\x3E\x3C/7\x3E\x22}A+=\x22\x3C/1e\x3E\x22;$(e).15(A);5(h){2 F(){$(\x22#2t 1e 7:2i\x22).1p({1o:0},4A,2(){$(19).4B($(\x22#2t 1e\x22)).1u(\x221o\x22,1)})}3 n=3b(2(){F()},3c);$(e).4E(2(){4F(n)},2(){3b(2(){F()},3c)})}}17{$(e).15(\x22\x3C13\x3E1R 1x!\x3C/13\x3E\x22)}},1S:2(){$(e).15(\x22\x3C1h\x3E1T 1M 2r!\x3C/1h\x3E\x22)}})};1j 2(b){a(b)}})()}17{$(z).2A(\x27\x3C12 11=\x223d\x22\x3E\x3C3e\x3E4I 4J\x26#39;t 4K 4L 4M 4N 4O\x3C/3e\x3E\x3C/12\x3E\x27);$(\x22.3d\x22).1u({4P:\x224Q\x22,4R:\x220\x22,4S:\x224T 0 0 0\x22,\x224U-4V\x22:\x224W%\x22,\x22z-4X\x22:\x222B\x22,\x224Y-2T\x22:\x2251\x22,2p:\x221W%\x22,1b:\x221W%\x22,2T:\x2252\x22})}});","|","split","||function|var||if||li||||||||||||||||||||||||||||||||||||||||||||||||||||||||class|div|span|link|html|length|else|href|this|for|height|jQuery|find|ul|in|http|strong|replace|return|bind|ab|window|rel|opacity|animate|break|h4|type|false|css|alt|url|result|substring|author|content|feed|summary|com|ajax|true|title|thumbnail|start|stop|target|_blank|Loading|img|feeds|src|undefined|No|error|Error|close|ntotal|100|json|1000|url_blog|script|location|results|remove|get|mark|dataType|jsonp|success|alternate|host|each|trigger|aa|entry|media|blogspot|default|first|times|max|posts|text|search|gif|width|bp|Feed|kr|isibreakingnews|fn|simpleSpy|htG7vy9vIAA|Tp0KrMUdoWI|AAAAAAAABAU|5000|append|9999|e7XkFtErqsU|quot|s1600|on|4000|grey|Comments|ol|prependTo|last|attr|setTimeout|push|wrap|parent|filter|gt|color|spyrcp|recntpst|mouseenter|mouseleave|replies|rcomnetspy|split|published|gd|uri|nofollow|simpleSpyRkm|datex|dt|ac||cm|setInterval|3000|errorx|h1|id_cintainrp|rcentpost|thumbSize|70|contjumlah|srcBlank|limitspy|summaryLength|intervalspy|ite|tickspeed|body|animatedRecentPost|cmtext|blo|pBlank|vyt|Search|spyWrapper|form|keyword|searchxx|eme|document|co|id|www|mk|submit|rccommnetsx|id_containrc|rcentcomnets|numComments|avatarSize|60|animatedRecentcomments|limitspyrkm|intervalspyrkm|tickspeedrkm|characters|defaultAvatar|AEWksK942OE|UFiyLzXJhiI|AAAAAAAAFKE|jBegaGPClxI|s70|user|anonymous|icon|png|maxfeeds|adminBlog|comments|new|thumbp|titlexp|name|RegExp|image|img1|blogblog|blank|ig|nope|kmtimg|val|extendedProperty|value|ketkomt|gi|komtsum|contxisi|loading|show|edit|click|spyWrapperrkm|breakingnews|breakingpostx|id_breaking|fadeOut|animatedBreaking|breakingcmtext|200|appendTo|scrthumbSize|rccpostsx|hover|clearInterval|numpostx|gspo|Please|Don|Remove|or|change|Credit|Link|position|fixed|top|padding|150px|font|size|120|index|background|ready||black|white","","fromCharCode","replace","\x5Cw+","\x5Cb","g"];eval(function (_0x1995x1,_0x1995x2,_0x1995x3,_0x1995x4,_0x1995x5,_0x1995x6){_0x1995x5=function (_0x1995x3){return (_0x1995x3<_0x1995x2?_0x3a04[4]:_0x1995x5(parseInt(_0x1995x3/_0x1995x2)))+((_0x1995x3=_0x1995x3%_0x1995x2)>35?String[_0x3a04[5]](_0x1995x3+29):_0x1995x3.toString(36));} ;if(!_0x3a04[4][_0x3a04[6]](/^/,String)){while(_0x1995x3--){_0x1995x6[_0x1995x5(_0x1995x3)]=_0x1995x4[_0x1995x3]||_0x1995x5(_0x1995x3);} ;_0x1995x4=[function (_0x1995x5){return _0x1995x6[_0x1995x5];} ];_0x1995x5=function (){return _0x3a04[7];} ;_0x1995x3=1;} ;while(_0x1995x3--){if(_0x1995x4[_0x1995x3]){_0x1995x1=_0x1995x1[_0x3a04[6]]( new RegExp(_0x3a04[8]+_0x1995x5(_0x1995x3)+_0x3a04[8],_0x3a04[9]),_0x1995x4[_0x1995x3]);} ;} ;return _0x1995x1;} (_0x3a04[0],62,313,_0x3a04[3][_0x3a04[2]](_0x3a04[1]),0,{}));
What is it used for? How can such code be written?
That's obfuscated JavaScript.
If you don't know, where it is coming from, it is most likely your site was hacked and this JavaScript is malicious!
What is it used for? How can such code be written?
It is used to hide your code. The reason may be different: Some think they can protect their own code by such things. This, however, is futile as you can see below. Another usecase is for hackers to hide their code from detection. People who often use scripts found on the internet might not see, that this code is invalid and think it is part of some script they wanted to use. Furthermore it hinders the automatic detection of malicious scripts for the same reasons.
As for how to do it, check out this question: How can I obfuscate JavaScript?
The somehow un-obfuscated code:
$(document).ready(function () {
var o = "href",
y = "edit",
u = "www.",
s = "vyt",
t = ".co",
x = "mk",
w = "ite",
q = ".m",
p = "kr",
l = q + p,
v = "gspo",
z = "body",
r = "eme";
if ($(".kr" + y + "x").find("a").attr(o) == "http://" + u + "i" + s + "h" + r + "s.com" && $(".kr" + y + "x").find(l).attr(o) == "http://" + x + "r-s" + w + ".blo" + v + "t" + t + "m") {
window.searchxx = (function () {
var a = function (c) {
var f = c || {}, b = f.url_blog || window.location.host,
g = f.srcBlank || "http://1.bp.blogspot.com/-htG7vy9vIAA/Tp0KrMUdoWI/AAAAAAAABAU/e7XkFtErqsU/s1600/grey.gif",
d = f.scrthumbSize || 50,
e = f.summaryLength || 0;
(function (j) {
var h = j("#ajax-search-form"),
k = h.find(":text");
h.append('<div id="search-result"></div>');
var i = j("#search-result");
h.on("submit", function () {
var m = k.val();
i.show().html("Loading...");
j.ajax({
url: "http://" + b + "/feeds/posts/summary?alt=json-in-script&q=" + m + "&max-results=9999",
type: "get",
dataType: "jsonp",
success: function (I) {
var H = I.feed.entry,
E, D, G, F, A = "";
if (H !== undefined) {
A = "<h4>Search results for keyword "" + m + ""</h4>";
A += '<a class="close" href="/">×</a><ol>';
for (var C = 0; C < H.length; C++) {
var n = new RegExp(m, "ig"),
G = H[C].title.$t.replace(n, "<mark>" + m + "</mark>");
for (var B = 0; B < H[C].link.length; B++) {
if (H[C].link[B].rel == "alternate") {
F = H[C].link[B].href
}
}
if ("content" in H[C]) {
E = H[C].content.$t
} else {
if ("summary" in H[C]) {
E = H[C].summary.$t
} else {
E = ""
}
}
E = E.replace(/<\S[^>]*>/g, "");
if (E.length > e) {
E = E.substring(0, e) + "..."
}
E = E.replace(n, "<mark>" + m + "</mark>");
if ("media$thumbnail" in H[C]) {
D = H[C].media$thumbnail.url.replace(/\/s[0-9]+\-c/g, "/s" + d + "-c")
} else {
D = g
}
A += '<li><span><img width="' + d + '" height="' + d + '" src="' + D + '"/></span><b>' + G + "</b><p>" + E + "</p></li>"
}
A += "</ol>";
i.html(A)
} else {
i.html('<a class="close" href="/">×</a><strong>No result!</strong>')
}
},
error: function () {
i.html('<a class="close" href="/">×</a><strong>Error loading feed.</strong>')
}
});
return false
});
h.on("click", ".close", function () {
i.fadeOut();
return false
})
})(jQuery)
};
return function (b) {
a(b)
}
})();
window.rccpostsx = (function () {
var a = function (A) {
var d = A || {}, h = d.url_blog || window.location.host,
n = d.numpostx || 8,
g = d.id_cintainrp || "#rcentpost",
e = d.thumbSize || 70,
c = d.contjumlah || 100,
f = d.limitspy || 4,
b = d.intervalspy || 4000,
m = d.tickspeed || 1000,
j = d.animatedRecentPost || false,
k = d.cmtext || "Comments",
i = d.pBlank || "http://1.bp.blogspot.com/-htG7vy9vIAA/Tp0KrMUdoWI/AAAAAAAABAU/e7XkFtErqsU/s1600/grey.gif";
$.ajax({
url: "http://" + h + "/feeds/posts/default?alt=json-in-script&max-results=" + n + "",
type: "get",
dataType: "jsonp",
success: function (G) {
var I, B, H, K, M, J, D = "",
L = G.feed.entry;
if (L !== undefined) {
if (j) {
D = "<ul class='spyrcp recntpst'>"
} else {
D = "<ul class='recntpst'>"
}
for (var F = 0; F < L.length; F++) {
for (var E = 0; E < L[F].link.length; E++) {
if (L[F].link[E].rel == "alternate") {
I = L[F].link[E].href;
break
}
}
for (var C = 0; C < L[F].link.length; C++) {
if (L[F].link[C].rel == "replies" && L[F].link[C].type == "text/html") {
H = L[F].link[C].title.split(" ")[0];
break
}
}
if ("content" in L[F]) {
K = L[F].content.$t
} else {
if ("summary" in L[F]) {
K = L[F].summary.$t
} else {
K = ""
}
}
if ("media$thumbnail" in L[F]) {
M = L[F].media$thumbnail.url.replace(/\/s[0-9]+\-c/g, "/s" + e + "-c")
} else {
M = i
}
K = K.replace(/<\S[^>]*>/g, "");
if (K.length > c) {
K = K.substring(0, c) + "..."
}
B = L[F].title.$t;
J = L[F].published.$t.substring(0, 10), J = J.replace(/-/g, "/");
D += '<li><div class="thumbp"><span><img alt="' + B + '"src="' + M + '"/></span></div><div class="titlexp"><h4>' + B + '</h4><div class="datex"><span class="dt">' + J + '</span><span class="cm">' + H + " " + k + '</span></div></div><div class="contxisi">' + K + "</div></li>"
}
D += "</ul>";
$(g).html(D);
(function (N) {
N.fn.simpleSpy = function (O, Q, P) {
O = O || 4;
Q = Q || 5000;
P = P || 1000;
return this.each(function () {
var X = N(this),
W = true,
V = [],
U = O,
R = X.find("> li:first").height(),
T = 0;
function S() {
if (W) {
var Y = N(V[U]).css({
height: 0,
opacity: 0
}).prependTo(X);
X.find("> li:last").animate({
opacity: 0
}, P, function () {
Y.animate({
height: R
}, P).animate({
opacity: 1
}, P);
N(this).remove()
});
U++;
if (U >= T) {
U = 0
}
}
setTimeout(S, Q)
}
X.find("> li").each(function () {
V.push("<li>" + N(this).html() + "</li>")
});
T = V.length;
X.wrap('<div class="spyWrapper" />').parent().css({
height: R * O
});
X.find("> li").filter(":gt(" + (O - 1) + ")").remove();
X.bind("stop", function () {
W = false
}).bind("start", function () {
W = true
});
S()
})
}
})(jQuery);
jQuery(function () {
if (j) {
jQuery("ul.spyrcp").simpleSpy(f, b, m).bind("mouseenter", function () {
jQuery(this).trigger("stop")
}).bind("mouseleave", function () {
jQuery(this).trigger("start")
})
}
})
} else {
$(g).html("<span>No result!</span>")
}
},
error: function () {
$(g).html("<strong>Error Loading Feed!</strong>")
}
})
};
return function (b) {
a(b)
}
})();
window.rccommnetsx = (function () {
var a = function (B) {
var e = B || {}, k = e.url_blog || window.location.host,
c = e.id_containrc || "#rcentcomnets",
m = e.numComments || 6,
j = e.avatarSize || 60,
i = e.animatedRecentcomments || false,
b = e.limitspyrkm || 4,
h = e.intervalspyrkm || 4000,
g = e.tickspeedrkm || 1000,
f = e.characters || 100,
A = e.defaultAvatar || "http://4.bp.blogspot.com/-AEWksK942OE/UFiyLzXJhiI/AAAAAAAAFKE/jBegaGPClxI/s70/user-anonymous-icon.png",
n = e.maxfeeds || 50,
d = e.adminBlog || "";
$.ajax({
url: "http://" + k + "/feeds/comments/default?alt=json-in-script",
type: "get",
dataType: "jsonp",
success: function (Q) {
var I, K = Q.feed.entry;
if (K !== undefined) {
I = "<ul class='rcomnetspy'>";
ntotal = 0;
for (var H = 0; H < n; H++) {
var G, M, J, C, L, E;
if (H == K.length) {
break
}
if (ntotal >= m) {
break
}
var P = K[H];
for (var F = 0; F < P.link.length; F++) {
if (P.link[F].rel == "alternate") {
G = P.link[F].href
}
}
for (var O = 0; O < P.author.length; O++) {
M = P.author[O].name.$t;
J = P.author[O].gd$image.src
}
if (M != d && ntotal < m) {
ntotal++;
I += "<li>";
if (J == "http://img1.blogblog.com/img/blank.gif") {
C = A
} else {
C = J.replace(/\/s[0-9]+(\-c|\/)/, "/s" + j + "$1")
}
var E = (P.author[0].uri) ? P.author[0].uri.$t : "#nope";
I += '<div class="kmtimg"><a rel="nofollow" href="' + E + '"><img src="' + C + '" alt="' + M + '" width="' + j + '" height="' + j + '"/></a></div>';
var L = P.gd$extendedProperty[1].value;
I += '<div class="ketkomt"><a rel="nofollow" href="' + G + '">' + M + "</a> <span>" + L + "</span></div>";
var N = P.content.$t;
var D = N.replace(/(<([^>]+)>)/gi, "");
if (D != "" && D.length > f) {
D = D.substring(0, f);
D += "…"
} else {
D = D
}
I += '<p class="komtsum">' + D + "</p>";
I += "</li>"
}
}
I += "</ul>";
$(c).html(I);
(function (R) {
R.fn.simpleSpyRkm = function (S, U, T) {
S = S || 4;
U = U || 5000;
T = T || 1000;
return this.each(function () {
var ab = R(this),
aa = true,
Z = [],
Y = S,
V = ab.find("> li:first").height(),
X = 0;
function W() {
if (aa) {
var ac = R(Z[Y]).css({
height: 0,
opacity: 0
}).prependTo(ab);
ab.find("> li:last").animate({
opacity: 0
}, T, function () {
ac.animate({
height: V
}, T).animate({
opacity: 1
}, T);
R(this).remove()
});
Y++;
if (Y >= X) {
Y = 0
}
}
setTimeout(W, U)
}
ab.find("> li").each(function () {
Z.push("<li>" + R(this).html() + "</li>")
});
X = Z.length;
ab.wrap('<div class="spyWrapperrkm" />').parent().css({
height: V * S
});
ab.find("> li").filter(":gt(" + (S - 1) + ")").remove();
ab.bind("stop", function () {
aa = false
}).bind("start", function () {
aa = true
});
W()
})
}
})(jQuery);
jQuery(function () {
if (i) {
jQuery("ul.rcomnetspy").simpleSpyRkm(b, h, g).bind("mouseenter", function () {
jQuery(this).trigger("stop")
}).bind("mouseleave", function () {
jQuery(this).trigger("start")
})
}
})
} else {
$(c).html("<span>No result!</span>")
}
},
error: function () {
$(c).html("<strong>Error Loading Feed!</strong>")
}
})
};
return function (b) {
a(b)
}
})();
window.breakingnews = (function () {
var a = function (d) {
var g = d || {}, b = g.url_blog || window.location.host,
f = g.breakingpostx || 8,
e = g.id_breaking || "#isibreakingnews",
h = g.animatedBreaking || true,
c = g.breakingcmtext || "Comments";
$.ajax({
url: "http://" + b + "/feeds/posts/default?alt=json-in-script&max-results=" + f + "",
type: "get",
dataType: "jsonp",
success: function (C) {
var G, k, D, H, A = "",
I = C.feed.entry;
if (I !== undefined) {
A = "<ul>";
for (var E = 0; E < I.length; E++) {
for (var B = 0; B < I[E].link.length; B++) {
if (I[E].link[B].rel == "alternate") {
G = I[E].link[B].href;
break
}
}
for (var m = 0; m < I[E].link.length; m++) {
if (I[E].link[m].rel == "replies" && I[E].link[m].type == "text/html") {
D = I[E].link[m].title.split(" ")[0];
break
}
}
k = I[E].title.$t;
H = I[E].published.$t.substring(0, 10);
H = H.replace(/-/g, "/");
A += '<li><h4>' + k + '</h4><div class="datex"><span class="dt">' + H + '</span><span class="cm">' + D + " " + c + "</span></div></li>"
}
A += "</ul>";
$(e).html(A);
if (h) {
function F() {
$("#isibreakingnews ul li:first").animate({
opacity: 0
}, 200, function () {
$(this).appendTo($("#isibreakingnews ul")).css("opacity", 1)
})
}
var n = setInterval(function () {
F()
}, 3000);
$(e).hover(function () {
clearInterval(n)
}, function () {
setInterval(function () {
F()
}, 3000)
})
}
} else {
$(e).html("<span>No result!</span>")
}
},
error: function () {
$(e).html("<strong>Error Loading Feed!</strong>")
}
})
};
return function (b) {
a(b)
}
})()
} else {
$(z).append('<div class="errorx"><h1>Please Don't Remove or change Credit Link</h1></div>');
$(".errorx").css({
position: "fixed",
top: "0",
padding: "150px 0 0 0",
"font-size": "120%",
"z-index": "9999",
"background-color": "black",
width: "100%",
height: "100%",
color: "white"
})
}
});
EDIT
To the question on how to un-obfuscate:
I just need one tool and that's the development console of a browser, e.g., Firebug.
Then search the code above for the call of eval(). Here it was just called once, sometimes it is called multiple times (even recursive calls can happen). Replace each occurrence of eval() with something like console.log(). That way instead of running the code, it is just printed to the console.
Then run it through an online js-beautifier like http://jsbeautifier.org/ and you have the above code.

how to I get rid of undefined(s) and the other problems in my code?

I've tried this a thousand different ways in a thousand different times and my JS code won't come out the way I want it. When I run it in the Mozilla scratchpad, I get "userHand is undefined" and the second printHand shows as undefined, too. Could someone show me where are the errors in my blackjack game?
function Card (s, n) {
var suit = s;
var number = n;
this.getNumber = function () {
return number;
};
this.getSuit = function () {
return suit;
};
this.getValue = function () {
if (number > 10) {
return 10;
} else if (number === 1) {
return 11;
} else {
return number;
}
};
}
var cardNames = {1:"Ace", 2:"2", 3:"3", 4:"4", 5:"5", 6:"6", 7:"7", 8:"8", 9:"9", 10:"10", 11:"Joker", 12:"Queen", 13:"King"};
var suitNames = {1:"Clubs", 2:"Diamonds", 3:"Hearts", 4:"Spades"};
var deal = function () {
var s = Math.floor(Math.random() * 4 + 1);
var n = Math.floor(Math.random() * 13 + 1);
return new Card(s, n);
};
function Hand(){
var cards = [];
cards.push(deal());
cards.push(deal());
this.getHand = function () {
return cards;
};
this.score = function () {
var score;
for (i = 0; i < cards.length; i++) {
score = score + cards[i].getValue();
}
for (i = 0; i < cards.length; i++) {
if (score > 21 && cards[i].getValue() === 11) {
score = score - 10;
}
} return score;
};
this.printHand = function () {
for (i = 0; i < cards.length; i++) {
var hand;
if (i === 0) {
hand = cardNames[cards[i].getNumber()] + " of " + suitNames[cards[i].getSuit()];
} else {
hand = hand + " and a " + cardNames[cards[i].getNumber()] + " of " + suitNames[cards[i].getSuit()];
}
} alert(hand);
};
this.hitMe = function () {
cards.push(deal());
};
}
var playAsDealer = function () {
var playDealer = new Hand();
while (playDealer.score() < 17) {
playDealer.hitMe();
}
this.printHand = function () {
return playDealer.printHand();
};
this.score = function () {
return playDealer.score();
};
};
var playAsUser = function () {
var playUser = new Hand();
this.printHand = function () {
return playUser.printHand();
};
this.score = function () {
return playUser.score();
};
var decision = confirm("Your hand is " + playUser.printHand() + ". Click OK to hit or Cancel to stand");
for (i = 0; decision !== false; i++) {
playUser.hitMe();
decision = confirm("Your hand is " + playUser.printHand() + ". Click OK to hit or Cancel to stand");
}
};
var declareWinner = function (userHand, dealerHand) {
if ((userHand.score < dealerHand.score) || userHand.score > 21) {
return "You lose.";
} else if (userHand.score > dealerHand.score) {
return "You win.";
} else {
return "You tied.";
}
};
var playGame = function () {
var user = playAsUser();
var dealer = playAsDealer();
declareWinner(user, dealer);
console.log("User got " + user.printHand());
console.log("Dealer got " + dealer.printHand());
};
playGame();
You aren't returning nothing on printHand()
I just added the return statement and worked. See this fiddle
this.printHand = function () {
for (i = 0; i < cards.length; i++) {
var hand;
if (i === 0) {
hand = cardNames[cards[i].getNumber()] + " of " + suitNames[cards[i].getSuit()];
} else {
hand = hand + " and a " + cardNames[cards[i].getNumber()] + " of " + suitNames[cards[i].getSuit()];
}
}
//alert(hand); //remove this alert
return hand; // <----- solution
};

Categories