javascript - 时间转换器 : split content time with ads time

标签 javascript arrays typescript

很抱歉,我正在尝试查找并解决一道数学题

假设我有 2 个列表或数组

内容数组

0-50 = C1
50-100 = C2

广告数组

10-20 = A1
30-60 = A2
80-140 = A3

输出应该是这样的

0-10 = C1
10-20 = A1
20-30 = C1
30-60 = A2
60-80 = C2
80-100 = A3

此处广告正在替换实际内容并将内容拆分为一组新的项目。

const content  = [
  {start: 0, end: 50, id: 'C1'},
  {start: 50, end: 100, id: 'C2'},
]

const ad = [
  {start:10, end: 20, id: 'A1' },
  {start:30, end: 60, id: 'A2' },
  {start:80, end: 140, id: 'A3' },
]

const newList = []
content.forEach(content => {
  ad.forEach((ad, index) => {
    //0 > 0 && 20 < 50
    if(content.start < ad.start && content.end > ad.end){
        newList.push({start: content.start, end: ad.start, id: content.id})
        newList.push(ad)
   }else{
        console.log(decodeURIComponent(`${content.start} > ${ad.start} && ${content.end} < ${ad.end}`))
    }
  })
})

console.log('newList',newList)

请帮忙

最佳答案

其实,我不知道我能对代码说些什么,试试这个方法:

const content  = [{start: 0, end: 50, id: 'C1'},{start: 50, end: 100, id: 'C2'}];
const ad = [{start:10, end: 20, id: 'A1' },{start:30, end: 60, id: 'A2' },{start:80, end: 140, id: 'A3' }];

const cPoints = content.flatMap(e => [e.start, e.end]); // [0, 50, 50, 100]
const aPoints = ad.flatMap(e => [e.start, e.end]); // [10, 20, 30, 60, 80, 140]
const rangeMin = Math.min(...cPoints); // 0
const rangeMax = Math.max(...cPoints); // 100
const rangePoints = [...new Set([...aPoints, ...cPoints])] // [10, 20, 30, 60, 80, 140, 0, 50, 100]
    .filter(point => (point >= rangeMin) && (point <= rangeMax)) // [10, 20, 30, 60, 80, 0, 50, 100]
    .sort((a, b) => a - b);  // [0, 10, 20, 30, 50, 60, 80, 100]
  
const getObjByPoint = (point, arr) => 
    arr.find((e) => (e.start <= point) && (point <= e.end));

const getFirstId = (point) => 
    (getObjByPoint(point, ad) || getObjByPoint(point, content)).id;
  
const result = rangePoints.reduce((acc, end, index, arr) => {
    if (index === 0) return acc;
    
    let start = arr[index - 1];
    const middle = (start + end) / 2;
    const id = getFirstId(middle);
    if (acc.at(-1)?.id === id) {
        start = acc.pop().start;
    }
    acc.push({ start, end, id });
    
    return acc;
}, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 时间转换器 : split content time with ads time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71871954/

相关文章:

python - 将对象属性值添加到数组 Django

javascript - 无法将属性设置为 null

typescript - 如何从现有的 JavaScript 库生成 .d.ts "typings"定义文件?

javascript - 如何在禁用 Javascript 时重定向(如新的 Twitter 布局)

javascript - 将选定的菜单选项移动到第一个位置

javascript - 客户端/服务器插值

angular - 通过在 typescript 中调用方法打开 bootstrap 4 模式

javascript - 使用 jquery addClass 到多个不同的元素

php - 如何展平 laravel 递归关系集合(树集合)?

c++ - 如何初始化嵌套结构数组