const regExpSync = (str, pat, fn) => {
let loc = 0;
let res;
while((res = pat.exec(str.substring(loc)))){
const rtn = fn(res);
if(rtn) return rtn;
loc += res.length + res.index;
}
};
const regExpAsync = async (str, pat, fn) => {
let loc = 0;
let res;
while((res = pat.exec(str.substring(loc)))){
const rtn = await fn(res);
if(rtn) return rtn;
loc += res.length + res.index;
}
};
const testPat = new RegExp('[a-z]+');
const testStr = '------aa-----abc--------zz--------dd----------';
console.log('-');
regExpSync(testStr, testPat, ([str]) => { console.log(str); return false; });
console.log('-');
await regExpAsync(testStr, testPat, async ([str]) => { console.log(str); return false; });
console.log('-');
I have almost identical async and synchronous code.
This is just an example, in reality it is more complex logic that has nothing to do with regular expressions.
Anyway, both work as callback function fn.
I am modifying both whenever there is a change in that logic.
Any ideas on minimizing that modification?
I tried the following but it's not very convenient.
Can we increase code reuse even just a little bit more here?
const regExp = (str, pat, fn) => {
if(fn.constructor.name == 'AsyncFunction') return (async () => {
let loc = 0;
let res;
while((res = pat.exec(str.substring(loc)))){
const rtn = await fn(res);
if(rtn) return rtn;
loc += res.length + res.index;
}
})();
else {
let loc = 0;
let res;
while((res = pat.exec(str.substring(loc)))){
const rtn = fn(res);
if(rtn) return rtn;
loc += res.length + res.index;
}
}
};