Skip to content

Instantly share code, notes, and snippets.

@yangchenyun
Last active October 28, 2017 01:02
Show Gist options
  • Save yangchenyun/863315fa474463efa4a71cc703e77732 to your computer and use it in GitHub Desktop.
Save yangchenyun/863315fa474463efa4a71cc703e77732 to your computer and use it in GitHub Desktop.
Compare two generator strings
function compareGen(leader, runner, leadStr='') {
const runnerNxt = runner.next();
if (runnerNxt.done) {
if (leadStr !== '') {
return false; // NOTE: The runner loses
}
const leaderNxt = leader.next();
if (leaderNxt.done) {
return true;
}
// NOTE: Leader isn't done yet.
if(leaderNxt.value == '') {
return compareGen(leader, runner, leadStr);
} else {
return false;
}
}
// Assert: runner isn't done yet.
let runnerStr = runnerNxt.value;
if (runnerStr.length <= leadStr.length) {
return leadStr.startsWith(runnerStr)
&& compareGen(leader, runner, leadStr.slice(runnerStr.length));
} else {
// NOTE: Swap runner and leader pointers
return runnerStr.startsWith(leadStr)
&& compareGen(runner, leader, runnerStr.slice(leadStr.length));
}
};
// Test cases
function* listGen(l) {
for (let el of l) {
yield el;
}
}
function testcompareGen(a, b, expected) {
if (compareGen(listGen(a), listGen(b)) != expected) {
console.error(`Expected [${a}], [${b}] to be ${expected}`);
} else if (compareGen(listGen(b), listGen(a)) != expected) {
console.error(`Expected [${b}], [${a}] to be ${expected}`);
} else {
console.log(`passed for: [${a}], [${b}] ${expected}`);
}
}
testcompareGen([""], [""], true);
testcompareGen([""], ["", ""], true);
testcompareGen(["a"], ["a"], true);
testcompareGen(["a"], ["", "a"], true);
testcompareGen(["a"], ["a", ""], true);
testcompareGen(["aa"], ["a", "a"], true);
testcompareGen([""], [" "], false);
testcompareGen(["a"], ["b"], false);
testcompareGen(["a"], ["a", " "], false);
testcompareGen(["a"], [" ", "a"], false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment