[英]JavaScript code optimization with ES6 standards
我对 ES6 不是很厉害,所以期待能得到一个小手:c。 如何优化此代码以获得更好的视觉外观? 我尝试了以下解决方案,但是,我确信我可以在这里使用数组Array.prototype
方法,如.map()
或类似方法。 这里的想法是确保 const 列表永远不会undefined
,如果它们是 - 使用右侧的情况:
function getLeadingComments(context) {
const contextOptions = context?.options[0];
const description = contextOptions?.description || 'React based Progressive Web App';
const author = contextOptions?.author || '';
const license = contextOptions?.license || 'OSL-3.0';
const packageName = contextOptions?.package || 'Powered by My Project';
return `/**
* ${description}
*
* Copyright © ${author}. All rights reserved.
* See LICENSE for license details.
*
* @license ${license}
* @package ${packageName}
*/
`;
}
正如Ivar
所说,可选链接是在ES2020中引入的,如果左侧操作数是null
或undefined
,您可以使用Nullish 合并运算符 (??)返回右侧。
function getLeadingComments(context) {
const contextOptions = context?.options[0];
const description =
contextOptions?.description ?? "React based Progressive Web App";
const author = contextOptions?.author ?? "";
const license = contextOptions?.license ?? "OSL-3.0";
const packageName = contextOptions?.package ?? "Powered by My Project";
return `
/*
* ${description}
*
* Copyright © ${author}. All rights reserved.
* See LICENSE for license details.
*
* @license ${license}
* @package ${packageName}
*/
`;
}
getLeadingComments({
options: [
{
description: "Incoming Data Description",
author: "Incoming Data Author",
license: "Incoming Data License",
package: "Incoming Data Package",
},
],
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.