Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

snippets,一些有用的小代码片段 #256

Open
oakland opened this issue Sep 17, 2020 · 0 comments
Open

snippets,一些有用的小代码片段 #256

oakland opened this issue Sep 17, 2020 · 0 comments

Comments

@oakland
Copy link
Owner

oakland commented Sep 17, 2020

单例模式,缓存内容

node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js 开头就有一段代码很有代表性,可以生成一个缓存,或者说单例。

 var isOldIE = function isOldIE() {
   var memo;
   return function memorize() {
     if (typeof memo === 'undefined') {
       // Test for IE <= 9 as proposed by Browserhacks
       // @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805
       // Tests for existence of standard globals is to allow style-loader
       // to operate correctly into non-standard environments
       // @see https://github.com/webpack-contrib/style-loader/issues/177
       memo = Boolean(window && document && document.all && !window.atob);
     }

     return memo;
   };
 }();

这段代码的模式可以借鉴,作为缓存或者单例模式的应用。

写函数文档的一种方式

以后写一个方法的文档可以使用这种方式,可选参数,参数类型都很清楚,从 webpack 的 loader interface 文档中借鉴来的: https://webpack.js.org/api/loaders/

this.callback(
  err: Error | null,
  content: string | Buffer,
  sourceMap?: SourceMap,
  meta?: any
);

转成驼峰名称的方式, camelCase

'hello world'.replace(/[- _]([a-z])/g, (str, ch) => ch.toUpperCase());

驼峰转中划线

'preventHandleCancelOnclickOverlay'.replace(/([a-z])([A-Z])([a-z])/g, (str, p1, p2, p3) => `${p1}-${p2.toLowerCase()}${p3}`); // prevent-handle-cancel-onclick-overlay

~~ 操作

看大数相加算法的时候,看到了这个操作符。见 JavaScript-Algorithms/issues/32 的第一个回答。

what-is-the-double-tilde-operator-in-javascript

That ~~ is a double NOT bitwise operator.
It is used as a faster substitute for Math.floor() for positive numbers. It does not return the same result as Math.floor() for negative numbers, as it just chops off the part after the decimal (see other answers for examples of this).

Worth noting that it differs from .floor() in that it actually just removes anything to the right of the decimal. This makes a difference when used against a negative number. Also, it will always return a number, and will never give you NaN. If it can't be converted to a number, you'll get 0.

获取 package-lock.json 中所有依赖的 license

可以考虑写成一个 npm 包,发布到 npm 仓库里。

const fs = require('fs');
const packageLock = require('./package-lock.json');

let result = [];

function getLicense(prePath, pkg) {
  try {
    const packageJson = require(`${prePath}/${pkg}/package.json`);
    const license = packageJson.license || '-';
    const version = packageJson.version || '-';
    result.push(`${pkg},${version},${license}`)
  } catch(e) {
    result.push(`${pkg},-,-`)
    return;
  }
}

function getResult(deps, pkg, prePath = './node_modules') {
  getLicense(prePath, pkg)
  if(!deps[pkg].dependencies) {
    return;
  };
  Object.keys(deps[pkg].dependencies).forEach(dep => getResult(deps[pkg].dependencies, dep, `${prePath}/${pkg}/node_modules`))
}

Object.keys(packageLock.dependencies).forEach(dep => getResult(packageLock.dependencies, dep))

function uniq(array) {
  const map = new Map();
  const result = [];
  array.forEach(item => {
    const [pkg] = item.split(',');
    if(map.has(pkg)) {
      return;
    }
    result.push(item);
    map.set(pkg, true);
  });
  return result;
}

fs.writeFileSync('./output.csv', uniq(['package,version,license', ...result]).join('\n'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant