Created
April 16, 2021 12:00
-
-
Save nobishino/ba595228d69f2cc684db80630adb0d6c to your computer and use it in GitHub Desktop.
Detect conflict between two path patterns.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// PathPattern codes | |
// "/hoge/:id" | |
// "/hoge/fuga/:name" | |
// "/hoge/fuga/hoho/:value" | |
// "/hoge/:param/fuga" | |
// | |
// :name = fuga AND :param = fuga | |
// | |
// PathPattern = ( Constant | Variable )を0個以上繰り返したもの | |
// | |
// 2つのPathPattern型の値が「衝突」するか判定するコードを書きたい | |
type Variable = ":variable"; | |
type Constant = string; | |
type PatternElement = Constant | Variable; | |
type PathPattern = PatternElement[]; | |
const parsePathPattern = (path :string) : PathPattern => { | |
return []; | |
}; | |
// Tests | |
type PathPatternTestCase = { | |
left : PathPattern, | |
right: PathPattern, | |
conflict: boolean, | |
}; | |
const isVariable = (arg: any): arg is Variable => arg === ":variable"; | |
// conflicts returns true iff left & right patterns conflicts. | |
const conflicts = (left: PathPattern, right:PathPattern):boolean => { | |
if (left.length !== right.length) { | |
return false; | |
} | |
for (let i = 0; i < left.length; i++) { | |
if (isVariable(left[i])) continue; | |
if (isVariable(right[i])) continue; | |
if (left[i] === right[i]) continue; | |
return false; | |
} | |
return true; | |
}; | |
const test = () => { | |
console.log("TEST STARTED."); | |
const testcases = [ | |
{ | |
left: ["hoge","fuga"], | |
right:["hoge","fuga"], | |
conflict: true, | |
}, | |
{ | |
left: ["hoge",":variable"], | |
right:["hoge","fuga"], | |
conflict: true, | |
}, | |
{ | |
left: ["hoge",":variable"], | |
right:["hoge","fuga","hoho"], | |
conflict: false, | |
}, | |
{ | |
left: ["hoge","fuga", ":variable"], | |
right:["hoge",":variable","hoho"], | |
conflict: true, | |
}, | |
]; | |
for (let i = 0; i < testcases.length; i++ ) { | |
const testcase = testcases[i]; | |
if (conflicts(testcase.left, testcase.right) !== testcase.conflict) { | |
console.error(`FAIL in case ${i}`, testcase); | |
} else { console.log(`SUCCESS case ${i}`);} | |
} | |
}; | |
test(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment