简渔:记一次简单的AI 代码调教

279 阅读1分钟

有时候代码就是写的垃圾,还好现在AI时代。能够给一些建议。但是你得有你的想法!是你的想法~

不废话 往下看

  1. 我就想要一段代码,js处理文件大小,美化显示 xx KB , xx MB

豆包:

function convertBytes(bytes, unit) {
  switch(unit) {
    case 'KB':
      return bytes / 1024;
    case 'MB':
      return bytes / 1024 / 1024;
    case 'GB':
      return bytes / 1024 / 1024 / 1024;
    default:
      return bytes;
  }
}

// 使用示例
console.log(convertBytes(5 * 1024 * 1024, 'MB')); 

智普:

这也太简便了吧...

给我优化

就让豆包吧...

优化,感觉也还行?

function convertBytes(bytes, unit, level = 0) {
  const units = {KB: 1, MB: 2, GB: 3};
  if (unit in units) {
    if (level === units[unit]) {
      return bytes;
    }
    return convertBytes(bytes / 1024, unit, level + 1);
  }
  return bytes;
}

这传几个参数干嘛啊,我当时就不乐意了。

再优化

function convertBytes(bytes, unit) {
  const unitMap = {KB: 1, MB: 2, GB: 3, TB: 4, PB: 5}; // 可根据需要继续添加更多单位
  const level = unitMap[unit] || 0;
  return level > 0? convertBytes(bytes / 1024, unit, level - 1) : bytes;
}

好像感觉能接受了,

给我 优化!!

受不来一点~

function convertBytes(bytes) {
  const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
  let currentBytes = bytes;
  let unitIndex = 0;
  while (currentBytes >= 1024 && unitIndex < units.length - 1) {
    currentBytes = currentBytes / 1024;
    unitIndex++;
  }
  return { value: currentBytes, unit: units[unitIndex] };
}

好了,退下吧~

总结

把你的想法告诉AI

注意:是你的想法~~