Skip to content

Instantly share code, notes, and snippets.

@gwing33
Last active May 10, 2022 17:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gwing33/c149fa8d7e580ad03c40a1a65b92a2da to your computer and use it in GitHub Desktop.
Save gwing33/c149fa8d7e580ad03c40a1a65b92a2da to your computer and use it in GitHub Desktop.
Zip Lists, FUB Code Golf
<?php
/**
* FollowUpBoss: Real Estate Lead Management Software.
*
* @author Gerald Leenerts
* @copyright Copyright (c) 2022, Enchant LLC.
* @license Property of Enchant LLC. All rights reserved.
* @prettier
*/
declare(strict_types=1);
namespace richdesk\extensions\command;
function zip(array $firstArray, array $secondArray, array $acc = [], int $index = 0)
{
// If we are beyond the first array index, no need to continue
if (count($firstArray) <= $index) {
return $acc;
}
// Add first first item in the list
$acc[] = $firstArray[$index];
// The array we are zipping, if it is empty, then we are done, no need to proceed.
if (empty($secondArray[$index])) {
return $acc;
}
// Push on the zipped item
$acc[] = $secondArray[$index];
// Call the next iteration
return zip($firstArray, $secondArray, $acc, $index + 1);
}
function testZip(string $name, array $first, array $second, array $expected)
{
$actual = zip($first, $second);
if (json_encode($actual) === json_encode($expected)) {
echo $name . ' OK! ' . json_encode($actual) . "\n";
} else {
echo $name . " FAILED:\n";
echo ' expected: ' . json_encode($expected) . "\n";
echo ' actual: ' . json_encode($actual) . "\n";
}
}
class Gerald extends \richdesk\extensions\console\Command
{
protected $_quiet = ['run'];
public function run()
{
testZip('Test Zip 1', [], [], []);
testZip('Test Zip 2', [], [1, 2, 3], []);
testZip('Test Zip 3', [1, 2, 3], [], [1]);
testZip('Test Zip 4', [1, 2], [3], [1, 3, 2]);
testZip(
'Test Zip 5',
[1, 2, 3, 4, 5],
[11, 12, 13],
[1, 11, 2, 12, 3, 13, 4]
);
testZip('Test Zip 6', [9, 9, 9], [8, 8, 8], [9, 8, 9, 8, 9, 8]);
testZip('Test Zip 7', [1, 2, 3], [4, 5, 6, 7], [1, 4, 2, 5, 3, 6]);
}
}
@stevenwadejr
Copy link

One bit of feedback here from a PHP perspective:

if (count($firstArray) <= $index) {

On larger data sets, count() can be slow. If you don't actually care about how many items are in the set and only want to know if the current index item exists (without caring about what's next after that index), it's faster and cheaper to do isset($firstArray[$currentIndex]). You'd want to use isset() vs !empty() too, because PHP will see $arr[1] = 0 with the index of 1 and the value being "empty".

#php-isms

@gwing33
Copy link
Author

gwing33 commented May 10, 2022

Makes sense. I almost went that route but for some reason decided to keep it to count

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment