]> git.andy128k.dev Git - missing-tools.git/commitdiff
collection tools: columns & chunks
authorAndrey Kutejko <andy128k@gmail.com>
Sun, 22 Sep 2013 18:52:50 +0000 (21:52 +0300)
committerAndrey Kutejko <andy128k@gmail.com>
Sun, 22 Sep 2013 18:52:50 +0000 (21:52 +0300)
src/collectiontools.php [new file with mode: 0644]
t/CollectionTest.php [new file with mode: 0644]

diff --git a/src/collectiontools.php b/src/collectiontools.php
new file mode 100644 (file)
index 0000000..b2bfc04
--- /dev/null
@@ -0,0 +1,47 @@
+<?php
+
+final class Collections
+{
+    /*
+     * Example output:
+     *    1   4   7   9
+     *    2   5   8  10
+     *    3   6
+     */
+    public static function columns($collection, $columnsCount)
+    {
+        $count = count($collection);
+        $r = $count % $columnsCount;
+        $length = ($count - $r) / $columnsCount;
+        $columns = array();
+        $offset = 0;
+        for ($i = 0; $i < $columnsCount; ++$i) {
+            $l = $length + ($i < $r ? 1 : 0);
+            $columns[] = array_slice($collection, $offset, $l);
+            $offset += $l;
+        }
+        return $columns;
+    }
+
+    public static function chunks($collection, $size, $pad=false)
+    {
+        $result = array();
+        $chunk = array();
+        foreach ($collection as $item) {
+            $chunk[] = $item;
+            if (count($chunk) === $size) {
+                $result[] = $chunk;
+                $chunk = array();
+            }
+        }
+        $c = count($chunk);
+        if ($c != 0) {
+            if ($pad)
+                while ($c < $size)
+                    $chunk[] = null;
+            $result[] = $chunk;
+        }
+        return $result;
+    }
+}
+
diff --git a/t/CollectionTest.php b/t/CollectionTest.php
new file mode 100644 (file)
index 0000000..64a40d9
--- /dev/null
@@ -0,0 +1,34 @@
+<?php
+
+class CollectionsTest extends PHPUnit_Framework_TestCase
+{
+    public function testColumns()
+    {
+        $arr = array(
+            'apple',
+            'grapefruit',
+            'carrot',
+            'tomato',
+        );
+        $columns = Collections::columns($arr, 3);
+        $this->assertEquals(3, count($columns));
+        $this->assertEquals(2, count($columns[0]));
+        $this->assertEquals(1, count($columns[1]));
+        $this->assertEquals(1, count($columns[2]));
+    }
+
+    public function testChunks()
+    {
+        $arr = array(
+            'apple',
+            'grapefruit',
+            'carrot',
+            'tomato',
+        );
+        $chunks = Collections::chunks($arr, 3);
+        $this->assertEquals(2, count($chunks));
+        $this->assertEquals(3, count($chunks[0]));
+        $this->assertEquals(1, count($chunks[1]));
+    }
+}
+