Skip to content

Instantly share code, notes, and snippets.

@sean-nicholas
Last active June 19, 2018 16:37
Show Gist options
  • Select an option

  • Save sean-nicholas/e93068b08239eac55b7140e31fb4c9c4 to your computer and use it in GitHub Desktop.

Select an option

Save sean-nicholas/e93068b08239eac55b7140e31fb4c9c4 to your computer and use it in GitHub Desktop.
Example for a possible alterItems implementation
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))
@sean-nicholas
Copy link
Copy Markdown
Author

sean-nicholas commented Jun 19, 2018

Output:

​​​​​first [ { blub: '123', test: '456' }, { test: '456' } ]​​​​​
​​​​​​​​​​
​​​​​second [ { new: '123' }, { new: '123' } ]​​​​​
​​​​​​​​​​
​​​​​third [ { blub: '123', test: '456' }, { test: '456' } ]​​​​​
​​​​​​​​​​
​​​​​fourth [ { new: '123' }, { new: '123' } ]​​​​​
​​​​​​​​​​
​​​​​fifth [ { new: '123' }, { test: '456' } ]​​​​​

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment