Skip to content

Instantly share code, notes, and snippets.

@bgotink
Created November 27, 2024 20:07
Show Gist options
  • Save bgotink/55fd7e6d705af649d8bcc88fc68735b4 to your computer and use it in GitHub Desktop.
Save bgotink/55fd7e6d705af649d8bcc88fc68735b4 to your computer and use it in GitHub Desktop.
Simple script to match `an+b` type expressions
/**
* @param {number} value
* @param {string} pattern
*/
function matchesAnB(value, pattern) {
let a = 1, b = pattern;
if (pattern.includes('n')) {
[a, b] = pattern.split('n', 2);
}
let result = (value - (b || 0)) / (a || 1);
return /* value >= 0 && */ result >= 0 && Number.isInteger(result);
}
for (const [value, pattern] of [
[2, '2'],
[3, '2'],
[-2, '2'],
[2, 'n'],
[2, 'n+1'],
[2, 'n+2'],
[2, 'n+3'],
[3, 'n+3'],
[0, '2n+2'],
[2, '2n+2'],
[3, '2n+2'],
[4, '2n+2'],
[6, '-2n+4'],
[4, '-2n+4'],
[2, '-2n+4'],
[0, '-2n+4'],
]) {
console.log(`${value} matches ${pattern}`, matchesAnB(value, pattern));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment