Created
October 14, 2013 14:56
-
-
Save b1/6977021 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var unique = function(array) { | |
return array.reduce(function(memo, elem) { | |
if (memo.indexOf(elem) < 0) memo.push(elem); | |
return memo; | |
}, []); | |
}; | |
// Example | |
// | |
// var callback = function(error, data) {console.log('Done.', error, data);}; | |
// ajax('url', callback); | |
// ajax('url', 'data', callback); | |
// ajax({url: 'url', method: 'PATCH', data: 'data'}, callback); | |
// | |
var ajax = function(url, data, callback) { | |
var params = {}; | |
if (typeof url === 'object') { | |
params = url; | |
} else { | |
params.url = url; | |
if (typeof data === 'object') { | |
params.method = 'POST'; | |
} else { | |
callback = data; | |
} | |
} | |
if (params.method == null) params.method = 'GET'; | |
if (callback == null) callback = Function.prototype; | |
var xhr = new XMLHttpRequest(); | |
xhr.onreadystatechange = function() { | |
if (xhr.readyState === 4) callback(xhr.responseText); | |
}; | |
xhr.open(params.method, params.url, true); | |
xhr.send(params.data); | |
}; | |
// Extends the object with properties from another objects. | |
// Example | |
// | |
// extend({a: 5, b: 10}, {b: 15, c: 20, e: 50}) | |
// # => {a: 5, b: 15, c: 20, e: 50} | |
// | |
var extend = function() { | |
var result = {}; | |
var objects = [].slice.call(arguments); | |
objects.forEach(object) { | |
Object.keys(object).forEach(function(key) { | |
result[key] = object[key] | |
}); | |
}; | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment