我想开始改进我编写代码的方式,而不重复,著名的干净的代码,我想开始将它应用到已经使用的小函数。如何在不复制开关条件的情况下改进此代码?甚至创建一个类并使用多态性,因为函数超级相似
/**
* Wait for an element and type on it
* @param {puppeteer.Page} page - Context page
* @param {string} selector - Element selector (CSS, xpath)
* @param {string} text - Text to be typed in the element
* @param {string} waitType - Element type (CSS, xpath)
*/
const waitAndType = async (page, selector, text, waitType = 'selector') => {
switch (waitType) {
case 'selector':
await page.waitForSelector(selector)
break
}
await page.type(selector, text)
}
// ===========================================
/**
* Wait for an element and click on it
* @param {puppeteer.Page} page - Context page
* @param {string} selector - Element selector (CSS, xpath)
* @param {string} waitType - Element type (CSS, xpath)
*/
const waitAndClick = async (page, selector, waitType = 'selector') => {
switch (waitType) {
case 'selector':
await page.waitForSelector(selector)
break
case 'xpath':
await page.waitForXPath(selector)
break
}
await page.click(selector)
}
// ===========================================
// ===========================================
module.exports = {
waitAndType,
waitAndClick,
}
// ===========================================
您可以向您的函数传递一个额外的参数,例如actionType
。根据您的需要,它可以有两个或多个可能的值(键入并单击)。
你可以这样重写你的函数:
const waitAndPerformAction = async (page, selector, waitType = 'selector', actionType) => {
switch (waitType) {
case 'selector':
await page.waitForSelector(selector)
break
case 'xpath':
await page.waitForXPath(selector)
break
}
if(actionType === 'type') {
await page.type(selector)
} else if(actionType === 'click`) {
await page.click(selector)
}
}
你可以更进一步,在一个单独的文件(也许是一个常量文件)中定义你的action
,在那里你可以定义所有的动作类型,以避免在你的代码库中出现任何拼写错误。
类似:
const ACTION_TYPES = {
CLICK: 'click',
TYPE: 'type',
....
}
然后将ACTION_TYPES.CLICK
或ACTION_TYPES.TYPE
作为argument
传递给您的函数并修改您的waitAndPerformAction
函数。
const waitAndPerformAction = async (page, selector, waitType = 'selector', actionType) => {
switch (waitType) {
case 'selector':
await page.waitForSelector(selector)
break
case 'xpath':
await page.waitForXPath(selector)
break
}
await page[ACTION_TYPES[actionType]]();
}
最后调用你的函数为:
waitAndPerformAction(..other arguments, ACTION_TYPES.CLICK)