Skip to content

引入

ts
import {
  coalesce,
  getFlattenedDeps,
  deepSet,
  toHumpObj,
  extend
} from 't-comm';

// 不支持 tree-shaking 的项目
import {
  coalesce,
  getFlattenedDeps,
  deepSet,
  toHumpObj,
  extend
} from 't-comm/lib/object/index';

// 只支持 ESM 的项目
import {
  coalesce,
  getFlattenedDeps,
  deepSet,
  toHumpObj,
  extend
} from 't-comm/es/object/index';

coalesce(...args)

描述:多参数空值合并函数

参数

参数名类型描述
...argsany任意数量的参数

返回: any

第一个非null/undefined的参数值

示例

ts
coalesce(null, undefined, 'hello'); // 'hello'
coalesce(undefined, 0, 'x'); // 0  // 0 不是 null/undefined
coalesce(undefined, '', 'x'); // ''  // 空串也保留
coalesce(null, null, null); // null  // 全部都是 null/undefined 时返回最后一个参数
coalesce(); // undefined

getFlattenedDeps(deps)

描述:将嵌套的依赖关系打平为一维映射 递归遍历依赖关系图,将每个节点的所有直接和间接依赖打平为数组,并去重

参数

参数名类型描述
depsRecord.<string, Array<string>>依赖关系映射,key 为节点名,value 为其直接依赖的节点数组

返回: Record.<string, Array<string>>

打平后的依赖关系映射

示例

ts
const deps = {
  a: ['b', 'c'],
  b: ['d'],
  c: [],
  d: [],
};
const result = getFlattenedDeps(deps);
// { a: ['b', 'c', 'd'], b: ['d'], c: [], d: [] }

deepSet(keyStr, target, value)

描述:深度赋值

参数

参数名描述
keyStr以点拼接的 key,比如 foo.bar
target目标对象
value目标值

示例

ts
const obj = { a: { b: 1 } };
deepSet('a.c', obj, 2);

console.log(obj);
// { a: { b: 1, c: 2 } }

toHumpObj(obj)

描述:将对象中的key由下划线专为驼峰

参数

参数名类型描述
objobject对象

返回: object

转化后的对象

示例

typescript
const obj = {
  a_a: 'a',
  b_b: [
    {
      bb_b: 'b',
    },
  ],
  c: {
    dd_d: 'd',
    e: {
      ee_e: 'e',
    },
  },
};

toHumpObj(obj);
// { aA: 'a', bB: [ { bbB: 'b' } ], c: { ddD: 'd', e: { eeE: 'e' } } }

extend(to, from)

描述:将属性混合到目标对象中

参数

参数名类型描述
toobject目标对象
fromobject原始对象

返回: 处理后的对象

示例

typescript
const a = { name: 'lee' }
const b = { age: 3 }
extend(a, b)

console.log(a)

// => { name: 'lee', age: 3 }