Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time Converter: split content time with ads time

I'm sorry I have a trying to find & fix a math problem

Let's say I have 2 List or array

Content Array

0-50 = C1
50-100 = C2

AD Array

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

OutPut Should be Like this

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

Here ads are replacing actual content and splitting the content into a new array of items.

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)

Please Help

like image 274
Raj Avatar asked Feb 16 '26 08:02

Raj


1 Answers

Actually, I don't know what I can say about the code, just try this approach:

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; }
like image 168
Alexandr Belan Avatar answered Feb 18 '26 20:02

Alexandr Belan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!