【发布时间】:2021-03-11 16:23:31
【问题描述】:
我想开始改进我编写代码的方式,而不是复制它,著名的干净代码,我想开始将它应用到已经使用的小函数中。 在不复制 switch 条件 甚至 创建类 并使用 多态性 的情况下,我如何改进这段代码,因为函数是 超级相似的
/**
* 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,
}
// ===========================================
【问题讨论】:
标签: javascript puppeteer code-cleanup