Created
May 2, 2013 19:46
-
-
Save anonymous/5504852 to your computer and use it in GitHub Desktop.
Refactoring nested example to pure functions
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
Y.io.xhr = function (uri, options) { | |
options = options || {}; | |
return new Y.Promise(function (resolve, reject) { | |
var io = Y.io(url, { | |
// reference options directly to avoid insertion of unwanted options | |
// into Y.io() | |
method: options.method, | |
data: options.data, | |
headers: options.headers, | |
form: options.form, | |
timeout: options.timeout, | |
on: { | |
success: function (id, response) { | |
resolve(response); | |
}, | |
failure: function (id, response) { | |
reject(response); | |
} | |
} | |
}); | |
// expose abort. It is not a prototype function so it's ok to copy it | |
this.abort = io.abort; | |
}); | |
}; | |
Y.io.getJSON = function (url, options) { | |
var promise = Y.io.xhr(url, options); | |
return Y.mix(promise.then(function (xhr) { | |
return Y.JSON.parse(xhr.responseText); | |
}), { | |
// pass around the abort function | |
abort: promise.abort | |
}); | |
}; | |
var getData = (function () { | |
function fetchData(offset) { | |
return Y.io.getJSON('/foo' + offset); | |
} | |
function concatData(dataset, offset) { | |
if (dataset.length < 100) { | |
offset += 100; | |
return fetchData(offset).then(function (newDataset) { | |
return concatData(dataset.concat(newDataset), offset); | |
}); | |
} else { | |
return dataset; | |
} | |
} | |
return function getData(offset) { | |
return concatData([], offset); | |
}; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment