Create a gist now

Instantly share code, notes, and snippets.

// 1: how could you rewrite the following to make it shorter?
bar['doSomething' + (foo ? '' : 'Else')](el);
// 2: what is the faulty logic in the following code?
// It will always print "world" to the console because foo is undefined in the
// anonymous function's closure at the time of the shortcut attempt.
// 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? how would you affect the value of the bar
// property for both foo and bim? how would you add a method to foo and bim to
// console.log the value of each object's bar property? 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();
Thinger.prototype.log = function(){
// summary:
// Logs the 'bar' attribute of any Thinger.
console.log(this.bar);
}
Thinger.prototype.isBarChanged = (function(original){
// summary:
// Determines if the 'bar' attribute was changed from the default 'baz'
// value.
// returns:
// Boolean, true if 'bar' has been changed to something other than 'baz'.
// False otherwise.
return function(){
returns this.bar === original;
};
})(Thinger.prototype.bar);
foo.bar = "moo"; // modifies only foo's 'bar' attribute, not bim's.
Thinger.prototype.bar = "oink"; // modifies not only foo and bim's 'bar' attr,
// but any previously and yet-to-be created
// Thingers' 'bar' attributes as well.
// 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()
};
var attrs = [];
for(var i in myObjects){
if(myObjects.hasOwnProperty(i)){
myObjects[i].destroy();
attrs.push(i);
}
}
for(var i = 0, len = attrs.length; i < len; i++){
delete myObjects[attrs[i]];
}
// 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 yourArray = $.map(myArray, function(val){
return [val, val, val].join(' ');
});
// 6: how could you improve the following code?
$(function() {
var $foobar = $('#bar'); // because IDs have to be unique, we can simplify the selector.
$foobar.css({
'color': 'red',
'border': '1px solid blue'
})
.text('new text!')
.click(function() {
$(this).attr('title', 'new title')
.width('100px');
});
// like to keep this separate and not-chained to separate "setup" from triggering.
$foobar.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
}
})();
/*
This code is not built with the "A" of "AJAX" in mind - asynchronous execution. If the load callback isn't called immediately (the http response comes back immediately), foo will be undefined in the block underneath... I would introduce a timeout to wait until foo is set... JUST KIDDING! You could fix this in a number of ways:
1) Put the "important code" inside of the load callback.
2) Subscribe to a pubsub event channel before the dojo.xhrGet with the important code. Then inside the load callback - trigger an event on that channel when foo is received.
3) Store the configuration object for dojo.xhrGet outside of the function call in an object literal and do a dojo.connect on the 'load' function with the important code before passing the literal to xhrGet.
The option you should select is dependent on the situation.
*/
// 8: how could you rewrite the following code to make it shorter?
(function(d, $){
d.forEach(['foo', 'bar', 'baz', 'bop'], function (classname){
$('li.'+classname+' a').attr('title', 'i am '+classname);
});
})(dojo, dojo.query);
// 9: how would you improve the following code?
var thingerPrefix = '<p><span class="thinger">i am thinger ',
thingerSuffix = '</span></p>',
gizmoPrefix = '<p><span class="gizmo">i am gizmo ',
gizmoSuffix = '</span></p>',
thingerStrings = [],
gizmoStrings = [];
for (i = 0; i <= 100; i++) {
thingerStrings = thingerStrings.concat([thingerPrefix, i, thingerSuffix]);
gizmoStrings = gizmoStrings.concat([gizmoPrefix, i, gizmoSuffix]);
}
$('#thinger').append(thingerStrings.join(''));
$('#gizmo').append(thingerStrings.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;
}
// All values entered could possibly be strings (most likely the input value,
// but possibly by mistake in application code: the others) in which case the
// returned value would be a bunch of concatenated strings (not a real value
// that we're looking for)
// 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'
}
];
function comprehend(arr){
// summary:
// Iterates over the array that is passed in, and returns an array
// containing strings which describe the items in the array by name and
// a list of their extras - if available.
// returns:
// Comprehended array.
var result = [];
for(var i = 0, len = arr.length; i < len; i++){
var item = arr[i].name;
if(arr[i].extras && arr[i].extras.length > 0){
item = item + ' (' + arr[i].extras.join(', ') + ')';
}
result.push(item);
}
return result;
}
// BONUS: write code such that the following alerts "Hello World"
say('Hello')('World');
function say(str1){
return function(str2){
alert(str1 + ' ' + str2);
};
}
// 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 current day is less than 5 days from the end of the month, we will end
// up with an incorrect month value for those days that extend into the next month.
// Instead of this code, I would build date objects for each of the next 5 days
// (and including today) and construct my strings from those objects. The date
// class will automatically roll over to the next month if you have date values
// that are greater than the specified month's maximum number of days.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment