Pchp.Library.Arrays.ChunkInternal C# (CSharp) Method

ChunkInternal() static private method

Internal version of Chunk with deep-copy option.
static private ChunkInternal ( PhpArray array, int size, bool preserveKeys, bool deepCopy ) : PhpArray
array Pchp.Core.PhpArray
size int
preserveKeys bool
deepCopy bool
return Pchp.Core.PhpArray
        internal static PhpArray ChunkInternal(PhpArray array, int size, bool preserveKeys, bool deepCopy)
        {
            if (array == null)
            {
                //PhpException.ArgumentNull("array");
                //return null;
                throw new ArgumentNullException(nameof(array));
            }
            if (size <= 0)
            {
                //PhpException.InvalidArgument("array", LibResources.GetString("arg:negative_or_zero"));
                //return null;
                throw new ArgumentException(nameof(size));
            }

            // nothing to do:
            if (array.Count == 0)
                return new PhpArray();

            // number of chunks:
            int count = (array.Count - 1) / size + 1; // = ceil(Count/size):

            PhpArray chunk;
            PhpArray result = new PhpArray(count, 0);

            IEnumerator<KeyValuePair<IntStringKey, PhpValue>> iterator = array.GetEnumerator();

            // if deep-copies are required, wrapp iterator by enumerator making deep copies:
            if (deepCopy)
                iterator = PhpVariable.EnumerateDeepCopies(iterator);

            iterator.MoveNext();

            // all chunks except for the last one:
            for (int i = 0; i < count - 1; i++)
            {
                chunk = new PhpArray(size, 0);

                if (preserveKeys)
                {
                    for (int j = 0; j < size; j++, iterator.MoveNext())
                        chunk.Add(iterator.Current.Key, iterator.Current.Value);
                }
                else
                {
                    for (int j = 0; j < size; j++, iterator.MoveNext())
                        chunk.Add(iterator.Current.Value);
                }

                result.Add(chunk);
            }

            // the last chunk:
            chunk = new PhpArray((size <= array.Count) ? size : array.Count, 0);

            if (preserveKeys)
            {
                do { chunk.Add(iterator.Current.Key, iterator.Current.Value); } while (iterator.MoveNext());
            }
            else
            {
                do { chunk.Add(iterator.Current.Value); } while (iterator.MoveNext());
            }

            result.Add(chunk);

            // no deep copy is needed since it has already been done on chunks:
            return result;
        }