React 深度学习:invariant

path: packages/shared/invariant.js

源码

/**
 * 根据条件抛出固定格式的错误,允许使用 %s 作为变量的占位符
 * 
 * @param condition
 * @param format
 * @param a
 * @param b
 * @param c
 * @param d
 * @param e
 * @param f
 */
export default function invariant(condition, format, a, b, c, d, e, f) {
  validateFormat(format);

  if (!condition) {
    let error;
    if (format === undefined) {
      error = new Error(
        'Minified exception occurred; use the non-minified dev environment ' +
          'for the full error message and additional helpful warnings.',
      );
    } else {
      const args = [a, b, c, d, e, f];
      let argIndex = 0;
      error = new Error(
        format.replace(/%s/g, function() {
          return args[argIndex++];
        }),
      );
      error.name = 'Invariant Violation';
    }

    error.framesToPop = 1; // we don't care about invariant's own frame
    throw error;
  }
}
复制代码

从上面的代码,从中可以看到:

  • 使用 %s 作为占位符的字符串替换手段,这在 Java 语言的工具中常会见到。
  • .replace 方法 可以接受一个函数作为第二个参数,这个函数用来创建新子字符串。当他跟正则的 g 标志配置使用的时候,该函数会在每个匹配到的字符串时被调用。

但这个函数有一个缺陷,就是只能支持最多 6 个占位符。

扩展

export default function invariant(condition, format, ...args) {
  validateFormat(format);

  if (!condition) {
    let error;
    if (format === undefined) {
      error = new Error(
        'Minified exception occurred; use the non-minified dev environment ' +
          'for the full error message and additional helpful warnings.',
      );
    } else {
      let argIndex = 0;
      error = new Error(
        format.replace(/%s/g, function() {
          return args[argIndex++];
        }),
      );
      error.name = 'Invariant Violation';
    }

    error.framesToPop = 1; // we don't care about invariant's own frame
    throw error;
  }
}
复制代码

只是简单做了很小的修改,使用 es6 的扩展运算符对方法参数做了改造

转载于:https://juejin.im/post/5d05af4be51d4556db694a06

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值