JSFiddle - React, Tailwind, and code Playground

by tanvir_alam_shawn

JavaScript

var collections=[
    {value:20, next:"", prev: "", lastUpdated: false, isLoaked: false, pointer: false},
  {value:20, next:"", prev: "", lastUpdated: false, isLoaked: false, pointer: false},
  {value:20, next:"", prev: "", lastUpdated: false, isLoaked: false, pointer: false},
  {value:20, next:"", prev: "", lastUpdated: false, isLoaked: false, pointer: false},
  {value:20, next:"", prev: "", lastUpdated: false, isLoaked: false, pointer: false}
];
var maxValue = 100;
var totalValue = 0;
var toBeDistributedNext = 0;
var toBeDistributedPrev = 0;

for(i = 0; i < collections.length; i++) {
    collections[i].next = (i+1) % collections.length;
  collections[i].prev = i > 0 ? i-1 : collections.length-1;
}

collections[2].value = 25;
collections[2].pointer = true;

collections.forEach(function (collection) {
  totalValue += parseInt(collection.value);
});

if (totalValue > maxValue) {
    toBeDistributedNext = totalValue - maxValue;
} else {
    toBeDistributedPrev = maxValue - totalValue;
}

var currentPointer = collections.find(item => item.pointer === true);
for (let i = 0; i < toBeDistributedNext; i++) {
  var nextIndex = currentPointer.next;
  if (!collections[nextIndex].pointer) {
    collections[nextIndex].value--;
    collections[nextIndex].lastUpdated = true;
  } else {
    toBeDistributedNext++;
  }
  currentPointer = collections[nextIndex];
}

console.log("AFTER", collections)