Skip to content

Instantly share code, notes, and snippets.

@jgornick
Forked from rmurphey/screening.js
Created September 13, 2010 20:39
Show Gist options
  • Save jgornick/577994 to your computer and use it in GitHub Desktop.
Save jgornick/577994 to your computer and use it in GitHub Desktop.
JS: Interview Questions
// 1: how could you rewrite the following to make it shorter?
if (foo) {
bar.doSomething(el);
} else {
bar.doSomethingElse(el);
}
Answer:
bar[foo ? 'doSomething' : 'doSomethingElse'](el);
--------------------------------------------------------------------------------
// 2: what is the faulty logic in the following code?
var foo = 'hello';
(function() {
var foo = foo || 'world';
console.log(foo);
})();
Answer:
foo will always be set to "world" inside the closure because during execution context
var foo is being initialized as undefined and when the expression evaluates, foo
resolves to the local (undefined) instance and not the window's foo instance.
--------------------------------------------------------------------------------
// 3: given the following code:
// 3a. How would you override the value of the bar property for the variable foo
// without affecting the value of the bar property for the variable bim?
// 3b. How would you affect the value of the bar property for both foo and bim?
// 3c. How would you add a method to foo and bim to console.log the value of each
// object's bar property?
// 3d. How would you tell if the object's bar property had been overridden for
// the particular object?
var Thinger = function() {
return this;
};
Thinger.prototype = {
bar : 'baz'
};
var foo = new Thinger(),
bim = new Thinger();
Answer(s):
3a. foo.bar = 'whatever';
3b. Thinger.prototype.bar = 'blah';
3c. Thinger.prototype.getBar = function() { return this.bar };
console.log(foo.getBar());
console.log(bim.getBar());
3d. if (typeof foo.hasOwnProperty != 'undefined' && foo.hasOwnProperty('bar')) {
console.log('overridden');
} else if (foo.bar != Thinger.prototype.bar) { // fallback
console.log('overridden');
}
--------------------------------------------------------------------------------
// 4: given the following code, and assuming that each defined object has a
// 'destroy' method, how would you destroy all of the objects contained in the
// myObjects object?
var myObjects = {
thinger : new myApp.Thinger(),
gizmo : new myApp.Gizmo(),
widget : new myApp.Widget()
};
Answer:
for (var o in myObjects) myObjects[o].destroy();
--------------------------------------------------------------------------------
// 5: given the following array, create an array that contains the contents of
// each array item repeated three times, with a space between each item. so,
// for example, if an array item is 'foo' then the new array should contain an
// array item 'foo foo foo'. (you can assume the library of your choice is
// available)
var myArray = [ 'foo', 'bar', 'baz' ];
Answer:
var i, v, n, r = [];
while (myArray.length) {
v = myArray.shift(); i = -1; n = [];
while (++i < 3) { n.push(v); } r.push(n.join(' '));
}
console.log(r);
--------------------------------------------------------------------------------
// 6: how could you improve the following code?
$(document).ready(function() {
$('.foo #bar').css('color', 'red');
$('.foo #bar').css('border', '1px solid blue');
$('.foo #bar').text('new text!');
$('.foo #bar').click(function() {
$(this).attr('title', 'new title');
$(this).width('100px');
});
$('.foo #bar').click();
});
Answer:
$(document).ready(function() {
$('.foo #bar')
.css({
'color': 'red',
'border': '1px solid blue'
})
.text('new text!')
.click(function() {
$(this)
.attr('title', 'new title')
.width('100px');
}).click(); // fire click
});
});
--------------------------------------------------------------------------------
// 7: what issues do you see with the following code? how would you fix it?
(function() {
var foo;
dojo.xhrGet({
url : 'foo.php',
load : function(resp) {
foo = resp.foo;
}
});
if (foo) {
// run this important code
}
})();
Answer:
When the condition is executed, foo has the possibility of being null since the
AJAX request may not be finished. If you want a simple fix, place the "important
code" in the success handler.
--------------------------------------------------------------------------------
// 8: how could you rewrite the following code to make it shorter?
(function(d, $){
$('li.foo a').attr('title', 'i am foo');
$('li.bar a').attr('title', 'i am bar');
$('li.baz a').attr('title', 'i am baz');
$('li.bop a').attr('title', 'i am bop');
})(dojo, dojo.query);
Answer:
Assuming there is only one class specifed for each LI:
(function(d, $) {
$('li.foo, li.bar, li.baz, li.bop').forEach(function(node) {
node = $(node);
node.query('a').attr('title', 'i am ' + node.attr('class'));
});
})(dojo, dojo.query);
After sleeping on it answer:
(function(d, $) {
var types = ['foo', 'bar', 'baz', 'bop'], t;
while (types.length) {
t = types.shift();
$('li.' + t + ' a').attr('title', 'i am ' + t);
}
})(dojo, dojo.query);
--------------------------------------------------------------------------------
// 9: how would you improve the following code?
for (i = 0; i <= 100; i++) {
$('#thinger').append('<p><span class="thinger">i am thinger ' + i + '</span></p>');
$('#gizmo').append('<p><span class="gizmo">i am gizmo ' + i + '</span></p>');
}
Answer:
var i = -1, thingerHtml = [], gizmoHtml = [];
while (++i <= 100) {
thingerHtml.push('<p><span class="thinger">i am thinger ' + i + '</span></p>');
gizmoHtml.push('<p><span class="gizmo">i am gizmo ' + i + '</span></p>');
}
$('#thinger').append(thingerHtml.join(''));
$('#gizmo').append(gizmoHtml.join(''));
--------------------------------------------------------------------------------
// 10: a user enters their desired tip into a text box; the baseTotal, tax,
// and fee values are provided by the application. what are some potential
// issues with the following function for calculating the total?
function calculateTotal(baseTotal, tip, tax, fee) {
return baseTotal + tip + tax + fee;
}
Answer:
There aren't any checks against the arguments to make sure they are specified or
defaulted to 0.
I would rewrite like:
function calculateTotal(baseTotal, tip, tax, fee) {
return (+baseTotal || 0) + (+tip || 0) + (+tax || 0) + (+fee || 0);
}
--------------------------------------------------------------------------------
// 11: given the following data structure, write code that returns an array
// containing the name of each item, followed by a comma-separated list of
// the item's extras, if it has any. e.g.
//
// [ "Salad (Chicken, Steak, Shrimp)", ... ]
//
// (you can assume the library of your choice is available)
var menuItems = [
{
id : 1,
name : 'Salad',
extras : [
'Chicken', 'Steak', 'Shrimp'
]
},
{
id : 2,
name : 'Potato',
extras : [
'Bacon', 'Sour Cream', 'Shrimp'
]
},
{
id : 3,
name : 'Sandwich',
extras : [
'Turkey', 'Bacon'
]
},
{
id : 4,
name : 'Bread'
}
];
Answer:
var v, r = [];
while (menuItems.length) {
v = menuItems.shift();
r.push(v.name + (v.extras && v.extras.length
? ' (' + v.extras.join(', ') + ')' : ''));
}
console.log(r);
--------------------------------------------------------------------------------
// BONUS: what is the faulty logic in the following code? how would you fix it?
var date = new Date(),
day = date.getDate(),
month = date.getMonth(),
dates = [];
for (var i = 0; i <= 5; i++) {
dates.push(month + '/' + (day + i));
}
console.log('The next five days are ', dates.join(', '));
Answer:
Two things I can see faulty are the code produces 6 days including today and
doesn't account for days rolling over into a new month.
var date, day = +new Date, dates = [], i = 0, dayMilliseconds = 1000 * 60 * 60 * 24;
while (++i <= 5) {
day += dayMilliseconds;
date = new Date(day);
dates.push(date.getMonth() + '/' + date.getDate());
}
console.log('The next five days are ', dates.join(', '));
After sleeping on it answer:
var date = new Date, dates = [], i = 0, dayMilliseconds = 1000 * 60 * 60 * 24;
while (++i <= 5) {
date.setTime(+date + dayMilliseconds);
dates.push(date.getMonth() + '/' + date.getDate());
}
console.log('The next five days are ', dates.join(', '));
--------------------------------------------------------------------------------
/*
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2004 Sam Hocevar <[email protected]>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
*/
@paulirish
Copy link

Ace answers. You coulda chained that .click() in #6 though. :) Otherwise superfine.

@jgornick
Copy link
Author

Oh geez, didn't even see that! Good catch!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment