I was trying to understand the JavaScript on a website when I found a weird phenomenon. I enabled breakpoints for XHRs in devtools and was reading through the stack trace when it hit the breakpoint. The issue is this.
There would be a function definition that is something like:
function foo(someObject) {
//Some code
}
and when I went one more step up the stack trace to see the call to this function, I'd see something like:
bar(someobject);
The name of the call doesn't match the definition! Someone please explain how this works. Some references to articles would be appreciated too.
This may be a rookie question so thank you for the patience.
Edit 1 - Here are some screenshots:
This is at the last item in the stack. The code paused at line 1829. This is inside the function named _() starting at line 1805. If I jump one step back in the stack trace,
it jumps to line 268 of the same js file, where the function call is. But the call is to t.scheduleFn(), not to _(). I have checked and verified that the object passed in is identical to the object received at the definition. Please drop a comment if you need any more info.
If you need to see this live, please go to this website, turn on breakpoints for XHRs, enter any number into the input field, click on 'Get OTP' and look at the stack trace.
Edit 3 - Here's some of the code:
Please read the comments that I've added.
This is the function inside which the code paused:
function _(e) { //Note that this is the function name
const o = e.data,
c = o.target;
c[i] = !1,
c[h] = !1;
const l = c[r];
d || (d = c[s], g = c[a]),
l && g.call(c, 'readystatechange', l);
const u = c[r] = () =>{
if (c.readyState === c.DONE) if (!o.aborted && c[i] && 'scheduled' === e.state) {
const n = c[t.__symbol__('loadfalse')];
if (n && n.length > 0) {
const r = e.invoke;
e.invoke = function () {
const n = c[t.__symbol__('loadfalse')];
for (let t = 0; t < n.length; t++) n[t] === e && n.splice(t, 1);
o.aborted || 'scheduled' !== e.state || r.call(e)
},
n.push(e)
} else e.invoke()
} else o.aborted || !1 !== c[i] || (c[h] = !0)
};
return d.call(c, 'readystatechange', u),
c[n] || (c[n] = e),
T.apply(c, o.args), //The code paused here.
c[i] = !0,
e
}
If I went one step back to see the call to the function _() I see this:
scheduleTask(e, t) {
let n = t;
if (this._scheduleTaskZS) this._hasTaskZS && n._zoneDelegates.push(this._hasTaskDlgtOwner),
n = this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt, this._scheduleTaskCurrZone, e, t),
n || (n = t);
else if (t.scheduleFn) t.scheduleFn(t); //The debugger shows that this is where the call to _() happened.
else {
if (t.type != S) throw new Error('Task is missing scheduleFn.');
k(t)
}
return n
}
My question is simply, how can a call to t.scheduleFn() go to _(). Hope this is clear.
Related
I was only allowed to use google document for writing.
Could you please tell me what I did wrong? The recruiter wont get back to me when I asked her why I failed
Task 1:
Implement function verify(text) which verifies whether parentheses within text are
correctly nested. You need to consider three kinds: (), [], <> and only these kinds.
My Answer:
const verify = (text) => {
const parenthesesStack = [];
for( let i = 0; i<text.length; i++ ) {
const closingParentheses = parenthesesStack[parenthesesStack.length - 1]
if(text[i] === “(” || text[i] === “[” || text[i] === “<” ) {
parenthesisStack.push(text[i]);
} else if ((closingParentheses === “(” && text[i] === “)”) || (closingParentheses === “[” && text[i] === “]”) || (closingParentheses === “<” && text[i] === “>”) ) {
parenthesisStack.pop();
}
};
return parenthesesStack.length ? 0 : 1;
}
Task 2:
Simplify the implementation below as much as you can.
Even better if you can also improve performance as part of the simplification!
FYI: This code is over 35 lines and over 300 tokens, but it can be written in
5 lines and in less than 60 tokens.
Function on the next page.
// ‘a’ and ‘b’ are single character strings
function func2(s, a, b) {
var match_empty=/^$/ ;
if (s.match(match_empty)) {
return -1;
}
var i=s.length-1;
var aIndex=-1;
var bIndex=-1;
while ((aIndex==-1) && (bIndex==-1) && (i>=0)) {
if (s.substring(i, i+1) == a)
aIndex=i;
if (s.substring(i, i+1) == b)
bIndex=i;
i--;
}
if (aIndex != -1) {
if (bIndex == -1)
return aIndex;
return Math.max(aIndex, bIndex);
} else {
if (bIndex != -1)
return bIndex;
return -1;
}
};
My Answer:
const funcSimplified = (s,a,b) => {
if(s.match(/^$/)) {
return -1;
} else {
return Math.max(s.indexOf(a),s.indexOf(b))
}
}
For starters, I'd be clear about exactly what the recruiter asked. Bold and bullet point it and be explicit.
Secondly, I would have failed you from your first 'for' statement.
See my notes:
// Bonus - add jsdoc description, example, expected variables for added intention.
const verify = (text) => {
// verify what? be specific.
const parenthesesStack = [];
for( let i = 0; i<text.length; i++ ) {
// this could have been a map method or reduce method depending on what you were getting out of it. Rarely is a for loop like this used now unless you need to break out of it for performance reasons.
const closingParentheses = parenthesesStack[parenthesesStack.length - 1]
// parenthesesStack.length - 1 === -1.
// parenthesesStack[-1] = undefined
if(text[i] === “(” || text[i] === “[” || text[i] === “<” ) {
parenthesisStack.push(text[i]);
// “ will break. Use "
// would have been more performant and maintainable to create a variable like this:
// const textOutput = text[i]
// if (textOutput === "(" || textOutput === "[" || textOutput === "<") {
parenthesisStack.push(textOutput)
} else if ((closingParentheses === “(” && text[i] === “)”) || (closingParentheses === “[” && text[i] === “]”) || (closingParentheses === “<” && text[i] === “>”) ) {
parenthesisStack.pop();
// There is nothing in parenthesisStack to pop
}
};
return parenthesesStack.length ? 0 : 1;
// Will always be 0.
}
Not exactly what the intention of your function or logic is doing, but It would fail based on what I can see.
Test it in a browser or use typescript playground. You can write javascript in there too.
Hard to tell without the recruiter feedback. But i can tell that you missundertood the second function.
func2("mystrs", 's', 'm') // returns 5
funcSimplified("mystrs", 's', 'm') // returns 3
You are returning Math.max(s.indexOf(a),s.indexOf(b)) instead of Math.max(s.lastIndexOf(a), s.lastIndexOf(b))
The original code start at i=len(str) - 1 and decrease up to 0. They are reading the string backward.
A possible implementation could have been
const lastOccurenceOf = (s,a,b) => {
// Check for falsyness (undefined, null, or empty string)
if (!s) return -1;
// ensure -1 value if search term is empty
const lastIndexOfA = a ? s.lastIndexOf(a) : -1
const lastIndexOfB = b ? s.lastIndexOf(b) : -1
return Math.max(lastIndexOfA, lastIndexOfB)
}
or a more concise example, which is arguably worse (because less readable)
const lastOccurenceOf = (s,a,b) => {
const safeStr = s || '';
return Math.max(safeStr.lastIndexOf(a || undefined), safeStr.lastIndexOf(b || undefined))
}
I'm using a || undefined to force a to be undefined if it is an empty string, because:
"canal".lastIndexOf("") = 5
"canal".lastIndexOf(undefined) = -1
original function would have returned -1 if case of an empty a or b
Also, have you ask if you were allowed to use ES6+ syntax ? You've been given a vanilla JS and you implemented the equivalent using ES6+. Some recruiters have vicious POV.
i'm getting random syntax errors in js files, sometimes in my bundle, sometimes other files, like fabric.min.js which i know works fine, and i can't figure it out.
For example lately i got :
bundle.js Uncaught SyntaxError: Unexpected token ) at 2:261833
which point to this function :
return function (t, n, a, o) {
if (!e(n)) {
var u, l = !1, h = [];
if (e(t)) l = !0, f(n, h); else {
var d = r(t.nodeType);
if (!d && sr(t, n)) O(t, n, h, null, null, o); else {
if (d) {
if (1 === t.nodeType && t.hasAttribute(I) && (t.removeAttribute(I), a = !0), i(a) && A(t, n, h)) return S(n, h, !0), t;
u = t, t = new pt(c.tagName(u).toLowerCase(), {}, [], void 0, u)
}
var p = t.elm, m = c.parentNode(p);
if (f(n, h, p._leaveCb ? null : m, c.nextSibling(p)), r(n.parent)) for (var g = n.parent, y = v(n); g;) {
for (var _ = 0; _ < s.destroy.length; ++_) s.destroy[_](g);
if (g.elm = n.elm, y) {
for (var x = 0; x < s.create.length; ++x) s.create[x](ar, g);
var k = g.data.hook.insert;
if (k.merged) for (var T = 1; T < k.fns.length; T++) k.fns[T]()
} else ir(g);
g = g.parent
}
r(m) ? w([t], 0, 0) : r(t.tag) && b(t)// error here at 0)
}
}
return S(n, h, l), n.elm
}
r(t) && b(t)
}
which is a function inside vue, i think it's the patch function.
When browser is restarted, it fixes the issue for some times, but in the end it comes back.
I was thinking about SRI but since we use file:// protocol (app is loaded locally in a webview inside android), i can't do that.
I'm tracking this issue for weeks without success,
how can a valid file become invalid and trigger syntax error ? can it be some cache issue ?
I know it's kind of a broad question, and i don't have much code to show, if you have any idea on how i could debug that or what could be the culprit here, like filesystem/hardware issue.
Thanks.
I'm trying to play around with a JS plugin I found on Codrops:
http://tympanus.net/codrops/2013/04/17/background-slideshow/
I'm trying to get the slideshow to auto stop after X images. In my case 2 or 3. From what I understood of Mary Lou's code, the function to determine pause/play/next slide is here:
function d(q) {
var p = g.eq(h);
console.log('abc');
if (q === "next") {
h = h < n - 1 ? ++h : 0
} else {
if (q === "prev") {
h = h > 0 ? --h : n - 1
}
}
var o = g.eq(h);
p.css("opacity", 0);
o.css("opacity", 1)
}
This JS is found here:
http://tympanus.net/Blueprints/BackgroundSlideshow/js/cbpBGSlideshow.js
What I've tried till now is basically place break points in the code to see what happens where and this is the conclusion I've come to.
Any help figuring out the rest of the problem?
Thanks!
You can use an if statement to not do prevent the .css commands from being reached. The following should stop it on the third slide
function d(q) {
var p = g.eq(h);
console.log('abc');
if (q === "next") {
h = h < n - 1 ? ++h : 0
} else {
if (q === "prev") {
h = h > 0 ? --h : n - 1
}
}
var o = g.eq(h);
if(h !== 3) {
p.css("opacity", 0);
o.css("opacity", 1);
}
}
With this being said, I'd recommend stopping whatever is firing that function in the if statement instead. That way it's not running this function when it's not doing something
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
My first Question:Which is better publish a web site from visual studio,or upload it by filezilla?
I didn't try any of them but someone told me when using filezilla:when I try to access my website, i get a file listing and when i try to view one of them, i just get a html text version of my pages.
but then again he said filezilla keeps the website even if it goes offline,is visual studio also the same?
And my SECOND Questin:
This is a jquery or javascript function?am I right?(which one?)
I saw it in a source code of a site,why does it look strange?I can't understand it,it has been encrypted?how can I turn it to sth which is more understandable?
(function (a, b) {
function c(a) { return K.isWindow(a) ? a : a.nodeType === 9 ? a.defaultView || a.parentWindow : !1 } function d(a) { if (!cl[a]) { var b = H.body, c = K("<" + a + ">").appendTo(b), d = c.css("display"); c.remove(); if (d === "none" || d === "") { cm || (cm = H.createElement("iframe"), cm.frameBorder = cm.width = cm.height = 0), b.appendChild(cm); if (!cn || !cm.createElement) cn = (cm.contentWindow || cm.contentDocument).document, cn.write((H.compatMode === "CSS1Compat" ? "<!doctype html>" : "") + "<html><body>"), cn.close(); c = cn.createElement(a), cn.body.appendChild(c), d = K.css(c, "display"), b.removeChild(cm) } cl[a] = d } return cl[a] } function e(a, b) { var c = {}; return K.each(cr.concat.apply([], cr.slice(0, b)), function () { c[this] = a }), c } function f() { cs = b } function g() { return setTimeout(f, 0), cs = K.now() } function h() { try { return new a.ActiveXObject("Microsoft.XMLHTTP") } catch (b) { } } function i() { try { return new a.XMLHttpRequest } catch (b) { } } function j(a, c) { a.dataFilter && (c = a.dataFilter(c, a.dataType)); var d = a.dataTypes, e = {}, f, g, h = d.length, i, j = d[0], k, l, m, n, o; for (f = 1; f < h; f++) { if (f === 1) for (g in a.converters) typeof g == "string" && (e[g.toLowerCase()] = a.converters[g]); k = j, j = d[f]; if (j === "*") j = k; else if (k !== "*" && k !== j) { l = k + " " + j, m = e[l] || e["* " + j]; if (!m) { o = b; for (n in e) { i = n.split(" "); if (i[0] === k || i[0] === "*") { o = e[i[1] + " " + j]; if (o) { n = e[n], n === !0 ? m = o : o === !0 && (m = n); break } } } } !m && !o && K.error("No conversion from " + l.replace(" ", " to ")), m !== !0 && (c = m ? m(c) : o(n(c))) } } return c } ...
it countinues
Your friend told you non-sense or you understood it that way. There's more than plain file transfer in VS deploy solution (like compilation of your source code into a dll for example), that can be fine tuned and so. Filezilla on its side is just plain ftp : you send the files you wish to a server.
You're not supposed to ask 2 questions at the same time, but still, to your second question :
this looks a lot like javascript, and it probably was minimized. This is a technique in which a parser replaces variable names by short names (letters), removes whitespaces and line feeds, etc in order to make the file smaller. Oh and JQuery is actually a javascript framework so there's no big difference between both.
I have this JavaScript code to format a number for US dollars that was given many thumbs up on Stackoverflow. It works well in the latest web browsers, but it causes the JavaScript to fail in IE7. I was trying to use a function that didn't require JQuery because the rest of this project isn't using it:
function formatDollar(num) {
var p = num.toFixed(2).split(".");
return "$" + p[0].split("").reverse().reduce(function(acc, num, i, orig) {
return num + (i && !(i % 3) ? "," : "") + acc;
}, "") + "." + p[1];
}
IE7 to the user simply says "Error on Page". In debugging mode on IE7 is complains it isn't an expected Object for the form being submitted on the On Click line. If I remove the above function and have it pass the numbers without formatting it works in IE7. It also complains about the line that starts with the first "return". I have eliminated everything else from the JavaScript and this function is the culprit it appears.
The reduce function is only available in JavaScript 1.8 (ECMAScript 5) and above, which IE7 does not implement. If you're not already using any libraries that provide its functionality cross-browser, it can be implemented thus:
if (!Array.prototype.reduce) {
Array.prototype.reduce = function reduce(accumulator){
if (this===null || this===undefined) throw new TypeError("Object is null or undefined");
var i = 0, l = this.length >> 0, curr;
if(typeof accumulator !== "function") // ES5 : "If IsCallable(callbackfn) is false, throw a TypeError exception."
throw new TypeError("First argument is not callable");
if(arguments.length < 2) {
if (l === 0) throw new TypeError("Array length is 0 and no second argument");
curr = this[0];
i = 1; // start accumulating at the second element
}
else
curr = arguments[1];
while (i < l) {
if(i in this) curr = accumulator.call(undefined, curr, this[i], i, this);
++i;
}
return curr;
};
}
Alternatively, if you don't mind not using the simplified syntax of reduce, just replace it in your function with an equivalent loop (e.g. the while loop above, or a for varient).
Reference