Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Unix Match. Part 1 by s0me1
import assert from "assert";
function unixMatch(filename: string, pattern: string): boolean {
return theyMatch(filename, pattern);
function theyMatch(string, pattern) {
if (pattern.length === 0) {
if (string.length === 0) {
return true;
}
return false;
}
const pChar = pattern[0];
const sChar = string[0];
if (pChar === '*') {
const newPattern = pattern.slice(1);
let pos = string.length;
do {
const newString = string.slice(pos);
const flag = theyMatch(newString, newPattern);
if (flag) {
return true;
}
// else
pos--;
} while (pos > -1);
return false;
}
if (pChar === '?' && sChar !== undefined) {
return theyMatch(string.slice(1), pattern.slice(1));
}
if (pChar === sChar) {
return theyMatch(string.slice(1), pattern.slice(1));
}
return false;
}
}
console.log('Example:');
console.log(unixMatch('somefile.txt', '*'));
// These "asserts" are used for self-checking
assert.equal(unixMatch('somefile.txt', '*'), true);
assert.equal(unixMatch('other.exe', '*'), true);
assert.equal(unixMatch('my.exe', '*.txt'), false);
assert.equal(unixMatch('log1.txt', 'log?.txt'), true);
assert.equal(unixMatch('log12.txt', 'log?.txt'), false);
assert.equal(unixMatch('log12.txt', 'log??.txt'), true);
console.log("Coding complete? Click 'Check' to earn cool rewards!");
July 24, 2020
Comments: