Skip to content

Instantly share code, notes, and snippets.

@aadsm
Forked from rmurphey/screening.js
Created September 13, 2010 20:30
Show Gist options
  • Save aadsm/577973 to your computer and use it in GitHub Desktop.
Save aadsm/577973 to your computer and use it in GitHub Desktop.
// 1: how could you rewrite the following to make it shorter?
if (foo) {
bar.doSomething(el);
} else {
bar.doSomethingElse(el);
}
1) (foo?bar.doSomething:bar.doSomethingElse)(el); // <-- minimizers can still work here
2) bar[foo?"doSomething":"doSomethingElse"](el); // <-- goodbye method renaming
3) bar["doSomething"+(foo?"":"Else")](el);
// 2: what is the faulty logic in the following code?
var foo = 'hello';
(function() {
var foo = foo || 'world';
console.log(foo);
})();
/*
outer foo will never be accessible when you enter the function since it will be
shadowed by the local foo var, console.log will always print "world".
*/
// 3: given the following code, 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?
foo.bar = 'baz';
// how would you affect the value of the bar
// property for both foo and bim?
Thinger.prototype.bar = 'baz'; /* assuming it hasn't been set in the object
itself */
// how would you add a method to foo and bim to
// console.log the value of each object's bar property?
Thinger.prototype.printBar = function() {
console.log(this.bar);
};
// how would you tell if
// the object's bar property had been overridden for the particular object?
obj.hasOwnProperty("bar");
var Thinger = function() {
return this;
};
Thinger.prototype = {
bar : 'baz'
};
var foo = new Thinger(),
bim = new Thinger();
// 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()
};
for( var object in myObjects ) if( myObjects.hasOwnProperty(object) ) {
myObjects[object].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' ];
var newMyArray = [];
for( var i = 0; i < myArray.length; i++ ) {
newMyArray[i] = "% % %".replace(/%/g, myArray[i]);
}
// 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();
});
function onBarClick() {
$(this)
.attr('title', 'new title')
.width('100px');
}
$('.foo #bar')
.css({
'color': 'red',
'border': '1px solid blue'
})
.text('new text')
.click(onBarClick)
.click();
/*
I prefer to put click handlers in functions with proper semantic names, the
name depends on what the code wants to achieve...
Obs: I'm not really a jQuery user..
*/
// 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
}
})();
/*
foo might be undefined at the time of if() so that bit of important code might
never be executed.
to fix it i guess it depends on the objective of the code, put the important
code in a function and call it inside the load I would say.
*/
// 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);
(function(d, $){
d.forEach(['foo', 'bar', 'baz', 'bop'], function(className) {
$('li.'+className+' a').attr('title', 'i am '+className);
});
})(dojo, dojo.query);
/*
Obs: I'm not really a dojo user..
*/
// 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>');
}
var i = 0;
var tmpl = '<p><span class="%name">i am %name %i</span></p>';
var numStr = new Array(101).join(tmpl).replace(/%i/g, function() { return i++; });
$('#thinger').append(numStr.replace(/%name/g, "thinger"));
$('#gizmo').append(numStr.replace(/%name/g, "gizmo"));
/*
optionally:
['thinger', 'gizmo'].forEach(function(e) {
$('#'+e).append(numStr.replace(/%name/g, e));
});
*/
/*
It kind of sucks but I found it funny, it does avoid changing the DOM 100's of
times.
I have no idea if it's faster, there is no string concatenation in js at least,
hopefully the native join/replace implementations will be faster...
*/
// 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;
}
/*
god knows what the user typed in, anything from letters to negative numbers
that might make the total <= 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'
}
];
var result = [];
for( var i = 0, item; item = menuItems[i]; i++ ) {
result.push(item.name + (item.extras ? '('+item.extras.join(', ')+')' : '');
}
return result;
// 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(', '));
/*
If the start day is, say, 30, it will report day 33, 34 for instance, which
doesn't exist.
A possible fix is to increment the date object itself and getDate() and
getMonth() at every loop iteration.
Also, if we want to report the -next- five days I guess it should start at i =
1, that loop as it is, is creating a 6 item array.
*/
var date = new Date(),
dates = [],
dayInMs = 24*60*60*1000;
for (var i = 0; i < 5; i++) {
date.setTime(date.getTime() + dayInMs);
dates.push(date.getMonth() + '/' + date.getDate());
}
console.log('The next five days are ', dates.join(', '));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment