Skip to content

Instantly share code, notes, and snippets.

@hunterlord
Last active October 18, 2017 09:54
Show Gist options
  • Save hunterlord/0287f0dc851e8343d287f2b85cf31025 to your computer and use it in GitHub Desktop.
Save hunterlord/0287f0dc851e8343d287f2b85cf31025 to your computer and use it in GitHub Desktop.
简单语法实现一个pipe函数
export let pipe = (data, filters) => {
  (typeof filters === 'function' ? [filters] : filters).map(
    filter =>
      data = typeof filter === 'string' ? pipe[filter](data) : filter(data)
  );
  return data;
};

// 设置第一个默认管道
pipe.numeric = data => {
  if (typeof data === 'string') {
    data = data.replace(/[^\d]/g, '');
    return Number.parseInt(data);
  } else return data;
};

// 设置第二个默认管道
pipe.toArray = data => {
  data = `${data}`;
  const arr = [];
  for (let i = 0; i < data.length; i++) {
    arr.push(data.at(i));
  }
  return arr;
};

// DEMO
 const a = pipe('happy 2016', [
  'numeric', // 添加第一个管道处理
  'toArray', // 添加第二个管道处理
  // 添加临时定义管道处理函数
   d => d.toString().replace(/,/g, '-') 
]);
console.log(a); // 2-0-1-6
@javaboool
Copy link

good job

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment