Skip to content

Instantly share code, notes, and snippets.

@tuor4eg
Created June 15, 2018 08:26
Show Gist options
  • Save tuor4eg/6337115e1999faf14a535bab0c51b264 to your computer and use it in GitHub Desktop.
Save tuor4eg/6337115e1999faf14a535bab0c51b264 to your computer and use it in GitHub Desktop.
const noop = () => {};
const once = (fn) => {
let called = false;
return (...args) => {
if (called) return;
called = true;
fn(...args);
};
};
const filter = (args, func, cb = noop) => {
if (args.length === 0) {
cb(null, []);
return;
}
const oncedCallback = once(cb);
const results = [];
args.forEach(arg => func(arg, (err, files) => {
if (err) {
oncedCallback(err);
} else {
results.push([arg, files, args.indexOf(arg)]);
}
if (results.length === args.length) {
const sortedRes = results.sort((a, b) => a[2] > b[2]);
const check = sortedRes.reduce((acc, element) => element[1] ? [...acc, element[0]] : acc, []);
cb(null, check);
}
}));
};
export default filter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment