创建类 song.js

export default class Song{
    constructor({id,mid,singer,name,album,duration,image,url}){
      this.id = id
      this.mid = mid
      this.singer = singer      
      this.name = name
      this.album = album
      this.duration = duration
      this.image = image
      this.url = url
    }
}

工厂方法: 不直接调用new,直接返回实例的方法,代码的优化

expoort function createSong(musicData){
  return new Song({
      id:musicData.songid,
      mid:musicData.songmid,
      singer:filterSinger(musicData.singer),
      name:musicData.songname,
      album:musicData.albumname,
      duration:musicData.interval,
      img:"https://asd.hellio${musicData.albumid}kj",      
      url:'https://thirdparty.com${musicData.songid}.pm4.musci',
  })
}
function filterSinger(singer){
   let ret = [];
   if(!singer){
       return ''
   }
  singer.forEach((s) => {
      ret.push(s.name)
  })
  return ret.join('/')
}

使用类

import {creatSong} from 'common/js/song'

_nornallizeSongs(list){
  let ret = []
  list.forEach((item)=>{
      //对象结构赋值
      let {musicData} = item
      //转化 musicData --> song
      if(musicData.songid && musicData.albummid){
           ret.push(createSong(musicData))
         }
  })
  return ret;
}
Logo

前往低代码交流专区

更多推荐