Last active
June 1, 2018 14:14
Artigos | Array.reduce - O canivete suíço da programação funcional | Promise chaining
This file contains hidden or 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
const states = { | |
default: '_partials/default', | |
error: '_partials/error', | |
} | |
function compileTemplates(templates) { | |
return Object | |
.keys(templates) | |
.map(key => ({ | |
key, | |
value() { | |
return new Promise((resolve) => { | |
setTimeout(() => resolve({ | |
key, | |
value: (data) => `Template "${templates[key]}" compiled with "${data}"`, | |
}), 1000); | |
}); | |
}, | |
})) | |
.reduce((promise, { key, value }) => { | |
return promise.then((result) => { | |
return value().then(Array.prototype.concat.bind(result)); | |
}); | |
}, Promise.resolve([])); | |
} | |
function parsePromiseHash(hash) { | |
return new Promise((resolve) => { | |
const obj = hash | |
.reduce((templates, { key, value }) => { | |
templates[key] = value; | |
return templates; | |
}, {}); | |
resolve(obj); | |
}); | |
} | |
compileTemplates(states) | |
.then(parsePromiseHash) | |
.then(compiledTemplates => { | |
compiledTemplates.default('data'); /* Template "_partials/default" compiled with "data" */ | |
compiledTemplates.error('invalid'); /* Template "_partials/error" compiled with "invalid" */ | |
}) | |
.catch(console.log); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment