gpt4 book ai didi

javascript - 将 2 个函数转换为 1 个函数

转载 作者:行者123 更新时间:2023-11-30 23:58:55 24 4
gpt4 key购买 nike

以下是获取下拉列表中选项的 2 个函数。我想将其变成一个函数而不是两个不同的函数。根据fromtype/totype,有几个不同的选项。但大多数情况下,情况 A、I、W 等对于这两个功能都是常见的。如何将以下2个函数变成一个函数。

我正在考虑一个函数

const getOptionKey = (type, metaType) => {
switch (type) {
case 'A':
type = ['A'];
break;
case 'W1':
case 'W':
type = ['W'];
break;
case 'I':
type = ['I'];
break;
case 'E':
switch (metaType) {
case 'A':
type = ['A'];
break;
case 'W2':
fromType = ['W'];
break;
default:
fromType = [
'A',
'W',
'C',
'I',
'CK'
];
}
break;
default:
type = [];
}
}

但是我无法想出更好的解决方案来对不常见的 switch 情况进行分类。

const getFromTypeOptionKey = (fromType, fromMetaType) => {
switch (fromType) {
case 'A':
fromType = ['A'];
break;
case 'I':
fromType = ['I'];
break;
case 'W1':
case 'W':
fromType = ['W'];
break;
case 'R':
fromType = ['R'];
break;
case 'E':
switch (fromMetaType) {
case 'A1':
fromType = ['A'];
break;
case 'W2':
fromType = ['W'];
break;
case 'I1':
case 'L':
case 'CH':
case 'C1':
case 'AT':
fromType = ['C'];
break;
default:
fromType = [
'A',
'W',
'C',
'I',
'CK'
];
}
break;
default:
fromType = [];
}
return fromType;
};

const getToTypeOptionKey = (toType, toMetaType) => {
switch (toType) {
case 'A':
toType = ['A'];
break;
case 'CK':
toType = ['CK'];
break;
case 'I':
toType = ['I'];
break;
case 'W1':
case 'W':
toType = ['W'];
break;
case 'E':
switch (toMetaType) {
case 'A1':
toType = ['A'];
break;
case 'W2':
toType = ['W'];
break;
case 'I1':
case 'CW':
case 'C1':
case 'PD':
case 'PU':
case 'AT':
toType = ['C'];
break;
default:
toType = [
'A',
'W',
'C',
'I',
'CK'
];
}
break;
default:
toType = [];
}
return toType;
};

最佳答案

这里的

switch 大小写使它有点笨拙。使用一个对象和一些 if 语句怎么样:

// Easier to read here since made a tree
let mapping = {
A: ['A'],
I: ['I'],
W: ['W'],
W1: ['W'],
R: ['R'],
default: [],
E: {
A1: ['A'],
W2: ['W'],
I1: ['C'],
L: ['C'],
CH: ['C'],
C1: ['C'],
AT: ['C'],
default: ['A', 'W', 'C', 'I', 'CK'],
}
}

function get(fromType, fromMetaType) {
return (fromType === 'E')
? mapping['E'][fromMetaType] || mapping['E'].default
: mapping[fromType] || mapping.default;
}

console.log(get('A')); // [ 'A' ]
console.log(get('INVALID')); // []
console.log(get('E', 'INVALID')); // [ 'A', 'W', 'C', 'I', 'CK' ]
console.log(get('E', 'C1')); // [ 'C' ]
console.log(get('R', 'C1')); // [ 'R' ] note that the `C1` is discarded

关于javascript - 将 2 个函数转换为 1 个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60873226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com