Last active
June 19, 2018 16:37
-
-
Save sean-nicholas/e93068b08239eac55b7140e31fb4c9c4 to your computer and use it in GitHub Desktop.
Example for a possible alterItems implementation
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
| function alterItems(func) { | |
| if (!func) { | |
| func = () => { }; | |
| } | |
| if (typeof func !== 'function') { | |
| throw new errors.BadRequest('Function required. (alter)'); | |
| } | |
| return context => { | |
| let items = context; | |
| const isArray = Array.isArray(items); | |
| function getResult(result, item) { | |
| if (typeof result === 'object' && result !== null) { | |
| return result | |
| } else { | |
| return item | |
| } | |
| } | |
| const results = (isArray ? items : [items]).map( | |
| (item, index) => { | |
| let result = func(item, context); | |
| if (typeof result === 'object' && typeof result.then === 'function') { | |
| return result.then(result => getResult(result, item)) | |
| } | |
| return getResult(result, item) | |
| } | |
| ); | |
| hasPromises = results.some(result => typeof result === 'object' && typeof result.then === 'function') | |
| if (!hasPromises) return results | |
| return Promise.all(results) | |
| .then((items) => context = items) | |
| .then(() => context) | |
| }; | |
| }; | |
| console.log('first', alterItems(rec => { rec.test = '456' })([{ blub: '123' }, { test: '123' }])) | |
| console.log('second', alterItems(rec => ({ new: '123' }))([{ blub: '123' }, { test: '123' }])) | |
| alterItems(rec => new Promise(res => { | |
| rec.test = '456' | |
| res() | |
| }))([{ blub: '123' }, { test: '123' }]) | |
| .then((data) => console.log('third', data)) | |
| alterItems(rec => new Promise(res => { | |
| res({ new: '123' }) | |
| }))([{ blub: '123' }, { test: '123' }]) | |
| .then((data) => console.log('fourth', data)) | |
| alterItems(rec => { | |
| if (rec.blub === '123') { | |
| return new Promise(res => { | |
| res({ new: '123' }) | |
| }) | |
| } | |
| rec.test = '456' | |
| })([{ blub: '123' }, { test: '123' }]) | |
| .then((data) => console.log('fifth', data)) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: