I'm trying to implement a pattern matching using JavaScript and would like to ask for suggestions. The pattern is calculated based on the existence of the object arguments. I think the current pseudocode is too verbose. Is there any way I can simplify it? (Please ignore Param1 and Param2)
pseudocode:
Pattern1: if null(3,4,5,6)
Pattern2: if notNull(3,4,5,6)
Pattern3: if notNull(6) and null(3,4,5)
Pattern4: if notNull(5) and null(3,4,6)
Pattern5: if notNull(4) and null(3,5,6)
Pattern6: if notNull(3) and null(4,5,6)
Pattern7: if notNull(5,6) and null(3,4)
Pattern8: if notNull(4,6) and null(3,5)
Pattern9: if notNull(3,6) and null(4,5)
Pattern10: if notNull(4,5) and null(3,4)
Pattern11: if notNull(3,5) and null(4,6)
Pattern12: if notNull(3,4) and null(5,6)
Pattern13: if notNull(3,4,5) and null(6)
Pattern14: if notNull(3,4,6) and null(5)
Pattern15: if notNull(3,5,6) and null(4)
Pattern16: if notNull(4,5,6) and null(3)
Yes; if
function check(params, ...list) {
for (let i = 2; i < params.length; ++i) {
if (params[i] == null) {
if (list.includes(i)) return false;
} else if (!list.includes(i)) return false;
}
return true;
}
were defined, then you could write patterns thus:
Pattern3: if check(arguments, 6)
I refactored it by using the following pseudocode.
patterns = [
[false,false,false,false],
[true,true,true,true],
[false,false,false,true],
[false,false,true,false],
[false,true,false,false],
[true,false,false,false],
[false,false,true,true],
[false,true,false,true],
[true,false,false,true],
[false,true,true,false],
[true,false,true,false],
[true,true,false,false],
[true,true,true,false],
[true,true,false,true],
[true,false,true,true],
[false,true,true,true],
]
patterns.findIndex(pattern => /* do params match? */)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.