Bad Apples

Code Kata

by LyndseyB

JavaScript

function badApples(input) {
  // first remove all bad packages
  const applesWithoutBadPackages = input.filter(package => !package.every(apple => apple === 0));
  
  // then repackage bad apples
  const goodApples = applesWithoutBadPackages.reduce((goodPackages, package, index, packages) => {
  	const badApple = package.find(apple => apple === 0);
    
    if (badApple === 0) {    
    	// there's no bad apple in this package, so continue on
    	goodPackages.push(package);
      
      return goodPackages;
    }
    
    // there's a bad apple in this package    
    // find the next bad package and repackage
    const restOfPackages = packages.slice(index + 1);
      
    // find any other packages that have bad apples so that we can repackage them
    const nextBadPackageIndex = restOfPackages.findIndex(package => package.some(apple => apple === 0));
    
    if (nextBadPackageIndex > -1) {
    	// found another bad package, 
      // move the good apple into the current package in the correct order
      const goodAppleInNextBadPackage = restOfPackages[nextBadPackageIndex].find(apple => apple !== 0); 
    }
        
    return goodPackages;
  }, []);
  
  console.log(goodApples);
    
  return goodApples;
}

badApples([
	[1,3],
  [7,6],
  [7,2],
  [1,3],
  [0,1],
  [4,5],
  [0,3],
  [7,6]
]);