[英]Curry two different but similar functions
我有兩個不同但相似的函數來進行api調用。 我想知道是否有辦法咖喱他們?
const getNameMatches = async partialName=> {
const { data: documents} = await axios.get(
`api/Documents/SearchDocument?searchString=${partialName}`,
);
const { data: clients } = await axios.get('api/Clients/GetAll');
return documents.map(document=> ({
label: document.Name,
subLabel: clients.find(c => c.id === document.clientID)?.firstName,
value: document,
}));
const getAddressMatches = async partialAddress=> {
const { data: documents} = await axios.get(
`api/Documents/SearchDocumentByAddress?searchString=${partialAddress}`,
);
const { data: clients } = await axios.get('api/Clients/GetAll');
return documents.map(document=> ({
label: document.propertyAddress,
subLabel: clients.find(c => c.id === document.clientID)?.firstName,
value: document,
}));
我將兩個功能合並為一個功能,但我想對它們進行咖喱處理,並想知道這是否可行。
組合功能:
const getMatches = async (state, partialString) => {
const tabValue = state.tabValue;
const { data } = await axios.get(
`api/Documents/SearchDocument${
tabValue === 'Address' ? 'ByAddress' : ''
}?searchString=${partialString}`,
);
const { data: clients } = await axios.get('api/Clients/GetAll');
return data.map(loan => ({
label: tabValue === 'Name' ? document.name: document.propertyAddress,
subLabel: clients.find(c => c.id === loan.clientID)?.firstName,
value: document,
}));
};
唯一的區別是API URL和標簽。
這樣您就可以收集它們並使其通用
const getMatches = async (partialValue,type)=> {
let urlString="",label="";
if(type==='name'){
urlString="SearchDocument";
label="Name";
}else{
urlString="SearchDocumentByAddress";
label="propertyAddress";
}
const { data: documents} = await axios.get(
`api/Documents/${urlString}?searchString=${partialValue}`,
);
const { data: clients } = await axios.get('api/Clients/GetAll');
return documents.map(document=> ({
label: document[label],
subLabel: clients.find(c => c.id === document.clientID)?.firstName,
value: document,
}));
如果您確實想要currying ,則可以執行以下操作:
const searchFor = type => {
const path = type === 'name'
? 'SearchDocument'
: 'SearchDocumentByAddress';
const prop = type === 'name'
? 'Name'
: 'propertyAddress';
return function(string){
const apiDocs = `api/Documents/${path}?searchString=${string}`;
const apiClients = `api/Clients/GetAll`;
const documents = await axios.get(apiDocs);
const clients = await axios.get(apiClients);
return documents.map(document => ({
label: document[prop],
subLabel: clients.find(c => c.id === document.clientID).firstName,
value: document
}));
}
}
然后您可以這樣稱呼它:
const getNameMatches = searchFor('name');
getNameMatches('foobar');
/* OR */
const getAddrMatches = searchFor('address');
getAddrMatches('foobar');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.