Skip to content

Instantly share code, notes, and snippets.

@matthew-carroll
Last active August 29, 2015 14:03
Show Gist options
  • Save matthew-carroll/cd62bcd860307b9ef0bd to your computer and use it in GitHub Desktop.
Save matthew-carroll/cd62bcd860307b9ef0bd to your computer and use it in GitHub Desktop.
Example of functional programming in JavaScript
// Example of how one might do some functional programming in
// JavaScript. This example uses promises and presents a fictional
// process for taking a photo, creating a thumbnail, and saving
// them. Notice how the data is passed through all the functions
// instead of being stored in a higher scope.
obtainCamera()
.then(function(camera) {
// we receive a camera from obtainCamera()
camera.setZoom(5);
camera.enableAutofocus(true);
return camera.takePhoto();
})
.then(function(photo) {
// we receive a photo as output from the previous function
// we copy the photo and downsize it to become a thumbnail
var thumbnail = photo.copy();
thumbnail.resize(100, 100);
// we return an object containing the original photo and the
// new thumbnail
return {
photo: photo,
thumbnail: thumbnail
}
})
.then(function(photos) {
// we receive the photo and thumbnail, then we save them
return getDatabase().save(photo);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment