Dsheiko\Extras

Dsheiko\Extras is a collection of chainable high-order functions to abstract and manipulate PHP types. The library extends PHP types with JavaScript and Underscore.js methods

The packages takes its name from Array Extras referring to the array methods added in ES5 (JavaScript) to abstract generic array manipulation logic

Installation

Require as a composer dependency:

composer require "dsheiko/extras"

Highlights


Download

Dsheiko\Extras Cheatsheet

Overview

Overview

Dsheiko\Extras\Arrays

Overview examples

<?php
// Accept non-reference array
Arrays::each([1, 2, 3], function(){});

// Accept user defined / built-in functions
Arrays::each([1, 2, 3], "\\var_dump");
Arrays::each([1, 2, 3], [$this, "foo"]);

// Chain of calls
$res = Arrays::chain([1, 2, 3])
    ->map(function($num){ return $num + 1; })
    ->filter(function($num){ return $num > 1; })
    ->reduce(function($carry, $num){ return $carry + $num; }, 0)
    ->value();

Methods _.functions, _.extendOwn, _.clone are not implemented. Given we consider here JavaScript object as associative array, they are not relevant.

Method _.isElement depends on DOM and therefore is not applicable in PHP context.

Methods _.isArguments, _.isRegExp, _.isUndefined are not relevant in PHP context

Methods _.isFunction, _.isString, _.isNumber, _.isFinite, _.isNaN, _.isBoolean, _.isDate, _.isError, _.isNull belong to the corresponded classes Dsheiko\Extras\Functions, Dsheiko\Extras\Strings, Dsheiko\Extras\Numbers, Dsheiko\Extras\Booleans, Dsheiko\Extras\Any

JavaScript-inspired methods

assign

Copy the values of all properties from one or more target arrays to a target array.

Parameters
Syntax
 assign(array $array, ...$sources): array
Example
<?php
$res = Arrays::assign(["foo" => 1, "bar" => 2], ["bar" => 3], ["foo" => 4], ["baz" => 5]);
// $res === ["foo" => 4, "bar" => 3, "baz" => 5]

$res = Arrays::assign([10 => "foo", 20 => "bar"], [20 => "baz"]);
// $res === [ 10 => "foo", 20 => "baz" ]

concat

Merge two or more arrays

Parameters
Syntax
 concat(array $array, array ...$targets): array
Example
<?php
$res = Arrays::concat([1, 2], [3, 4], [5, 6]); // [1, 2, 3, 4, 5, 6]

copyWithin

Shallow copy part of an array to another location in the same array and returns it, without modifying its size.

Parameters
Syntax
 copyWithin(
        array $array,
        int $targetIndex,
        int $beginIndex = 0,
        int $endIndex = null
    ): array
Example
<?php
$res = Arrays::copyWithin([1, 2, 3, 4, 5], 0, 3, 4); // [4, 2, 3, 4, 5]

each

Iterate over a list of elements, yielding each in turn to an iteratee function

Parameters
Callback arguments
Syntax
each(array $array, mixed $mixed)
Example
<?php
$sum = 0;
Arrays::each([1, 2, 3], function ($val) use(&$sum) {
    $sum += $val;
});

entries / pairs

Convert an object into a list of [key, value] pairs.

Parameters
Syntax
 pairs(array $array): array
Example
<?php
$res = Arrays::pairs([
            "foo" => "FOO",
            "bar" => "BAR",
        ]);
// [["foo", "FOO"], ["bar", "BAR"]]

every

Test whether all elements in the array pass the test implemented by the provided function.

Parameters
Callback arguments
Syntax
 every(array $array, mixed $mixed): bool
Example
<?php
$res = Arrays::every([1, 2, 3], function($num){ return $num > 1; }); // false

fill

Fill all the elements of an array from a start index to an end index with a static value.

Parameters
Syntax
 fill(array $array, $value, int $beginIndex = 0, int $endIndex = null): array
Example
<?php
$res = Arrays::fill([1, 2, 3], 4); // [4, 4, 4]
$res = Arrays::fill([1, 2, 3], 4, 1); // [1, 4, 4]

filter

Look through each value in the list, returning an array of all the values that pass a truth test (predicate).

Parameters
Callback arguments
Syntax
 filter(array $array, callable $predicate): array
Example
<?php
$array = Arrays::filter([1, 2, 3], function($num){ return $num > 1; });

find

Look through each value in the list, returning the first one that passes a truth test (predicate),

Parameters
Callback arguments
Syntax
 find(array $array, callable $predicate)
Example
<?php
$value = Arrays::find([1, 2, 3], function($num){ return $num > 1; });

from

Create a new array from an array-like or iterable object

Parameters
Syntax
 from($collection): array
Example
<?php
$res = Arrays::from(new \ArrayObject([1,2,3])); // [1,2,3]

$obj = new \ArrayObject([1,2,3]);
$res = Arrays::from($obj->getIterator()); // [1,2,3]

hasOwnProperty

Return a boolean indicating whether the object has the specified property

Parameters
Syntax
 hasOwnProperty(array $array, mixed $key): bool
Example
<?php
$res = Arrays::hasOwnProperty(["foo" => "FOO"], "foo");// true

includes

Determine whether an array includes a certain element, returning true or false as appropriate.

Parameters
Syntax
 includes(array $array, $searchElement, int $fromIndex = null): bool
Example
<?php
$res = Arrays::includes([1, 2, 3], 2); // true
$res = Arrays::includes([1, 2, 3, 5, 6, 7], 2, 3); // false

indexOf

Return the first index at which a given element can be found in the array, or -1 if it is not present

Parameters
Syntax
 indexOf(array $array, $searchElement, int $fromIndex = 0): int
Example
<?php
$src = ["ant", "bison", "camel", "duck", "bison"];
$res = Arrays::indexOf($src, "bison"); // 1
$res = Arrays::indexOf($src, "bison", 2); // 4

is

Determine whether two values are the same value.

Parameters
Syntax
 is(array $array, array $arrayToCompare): bool
Example
<?php
$a = [1,2,3];
$b = [1,2,3];
$res = Arrays::is($a, $b); // true


$a = [[["foo" => "FOO", "bar" => "BAR"]]];
$b = [[["foo" => "FOO", "bar" => "BAR"]]];
$res = Arrays::is($a, $b); // true

join

Join all elements of an array into a mixed and returns this mixed.

Parameters
Syntax
 join(array $array, mixed $separator = ",")
Example
<?php
$res = Arrays::join([1,2,3], ":"); // "1:2:3"

keys

Return all the keys or a subset of the keys of an array

Parameters
Syntax
 keys(array $array, $searchValue = null): array
Example
<?php
$res = Arrays::keys(["foo" => "FOO", "bar" => "BAR"]); // ["foo", "bar"]
$res = Arrays::keys(["foo" => "FOO", "bar" => "BAR"], "BAR"); // ["bar"]

lastIndexOf

Return the last index at which a given element can be found in the array, or -1 if it is not present.

Parameters
Syntax
 lastIndexOf(array $array, $searchElement, int $fromIndex = null): int
Example
<?php
$src = [2, 5, 9, 2];
$res = Arrays::lastIndexOf($src, 2); // 3
$res = Arrays::lastIndexOf($src, 2, 2); // 0

map

Produce a new array of values by mapping each value in list through a transformation function

Parameters
Callback arguments
Syntax
 map(array $array, mixed $mixed): array
Example
<?php
// Map sequential array
$res = Arrays::map([1, 2, 3], function($num){ return $num + 1; });

// Map associative array
$res = Arrays::chain([
            "foo" => "FOO",
            "bar" => "BAR",
        ])
        ->pairs()
        ->map(function($pair){
          // key + value
          return $pair[0] . $pair[1];
        })
        ->value();

of

Create a new array with a variable number of arguments, regardless of number or type of the arguments.

Parameters
Syntax
 of(...$args): array
Example
<?php
 $res = Arrays::of(1, 2, 3); // [1, 2, 3]

pop

Remove the last element from an array and returns that element. This method changes the length of the array.

Parameters
Syntax
 pop(array &$array)
Example
<?php
 $src = [1, 2, 3];
 $res = Arrays::pop($src); // 3

push

Add one or more elements to the end of an array and returns the new length of the array.

Parameters
Syntax
 push(array $array, $value): array
Example
<?php
 $src = [1,2,3];
 $res = Arrays::push($src, 4); // [1, 2, 3, 4]

reduceRight

The right-associative version of reduce.

Parameters
Callback arguments
Syntax
 reduceRight(array $array, mixed $mixed, $initial = null)
Example
<?php
$res = Arrays::reduceRight([1,2,3], function(array $carry, int $num){
  $carry[] = $num;
  return $carry;
}, []);
// [3,2,1]

reduce

Boil down a list of values into a single value.

Parameters
Callback arguments
Syntax
 reduce(array $array, mixed $mixed, $initial = null)
Example
<?php
$sum = Arrays::reduce([1, 2, 3], function ($carry, $num) { return $carry + $num; }, 0);
// 6

reverse

Reverse an array in place. The first array element becomes the last, and the last array element becomes the first.

Parameters
Syntax
 reverse(array $array): array
Example
<?php
$res = Arrays::reverse([1,2,3]); // [3, 2, 1]

shift

Remove the first element from an array and returns that removed element. This method changes the length of the array.

Parameters
Syntax
 shift(array &$array)
Example
<?php
$src = [1, 2, 3];
$res = Arrays::shift($src); // 1

slice

Return a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

Parameters
Syntax
 slice(array $array, int $beginIndex, int $endIndex = null): array
Example
<?php
$src = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
$res = Arrays::slice($src, 1, 3); // ["Orange","Lemon"]

some

Test whether at least one element in the array passes the test implemented by the provided function

Parameters
Callback arguments
Syntax
 some(array $array, mixed $mixed): bool
Example
<?php
$res = Arrays::some([1, 2, 3], function($num){ return $num > 1; }); // true

sort

Sort an array by values (using a user-defined comparison function when callback provided)

Parameters
Syntax
 sort(array $array, mixed $mixed = null): array
Example
<?php
$res = Arrays::sort([3,2,1]);  // [1,2,3]

$res = Arrays::sort([3,2,1], function($a, $b){
            return $a <=> $b;
        });  // [1,2,3]

splice

Change the contents of an array by removing existing elements and/or adding new elements.

Parameters
Syntax
 splice(array $array, int $beginIndex, int $deleteCount = null, ...$items): array
Example
<?php
// remove 1 element from index 2, and insert "trumpet"
$src = ["angel", "clown", "drum", "sturgeon"];
$res = Arrays::splice($src, 2, 1, "trumpet"); // ["angel", "clown", "trumpet", "sturgeon"]

unshift

Add one or more elements to the beginning of an array and returns the new length of the array

Parameters
Syntax
 unshift(array &$array, ...$values)
Example
<?php
$src = [1, 2];
$src = Arrays::unshift($src, 0); // [0, 1, 2]
$res = Arrays::unshift($src, -2, -1); // [-2, -1, 0, 1, 2]

values

Return all the values of an array

Parameters
Syntax
 values(array $array): array
Example
<?php
$res = Arrays::values([ 5 => 1, 10 => 2, 100 => 3]); // [1,2,3]

Underscore.js\Collections methods

where

Look through each value in the list, returning an array of all the values that contain all of the key-value pairs listed in $conditions

Parameters
Syntax
 where(array $array, array $conditions): array
Example
<?php
$listOfPlays = [
    ["title" => "Cymbeline", "author" => "Shakespeare", "year" => 1611],
    ["title" => "The Tempest", "author" => "Shakespeare", "year" => 1611],
    ["title" => "Hamlet", "author" => "Shakespeare", "year" => 1603]
];
$res = Arrays::where($listOfPlays, ["author" => "Shakespeare", "year" => 1611]);
// [
//    ["title" => "Cymbeline", "author" => "Shakespeare", "year" => 1611],
//    ["title" => "The Tempest", "author" => "Shakespeare", "year" => 1611],
// ]

findWhere

Looks through the list and returns the first value that matches all of the key-value pairs listed in properties.

Parameters
Syntax
 findWhere(array $array, array $props)
Example
<?php
$src = [
    [
        "foo" => "FOO",
        "bar" => "BAR",
        "baz" => "BAZ",
    ],
    [
        "bar" => "BAR",
        "baz" => "BAZ",
    ],
    [
        "baz" => "BAZ",
    ]
];
$res = Arrays::findWhere($src, [
    "foo" => "FOO",
    "bar" => "BAR",
]);
//    [
//        "foo" => "FOO",
//        "bar" => "BAR",
//        "baz" => "BAZ",
//    ]

reject

Return the values in list without the elements that the predicate passes. The opposite of filter.

Parameters
Syntax
 reject(array $array, mixed $predicate)
Example
<?php
$res = Arrays::reject([1, 2, 3, 4, 5, 6], function ($num){
    return $num % 2 == 0;
}); // [1,3,5]

contains

Returns true if the value is present in the list.

Parameters
Syntax
 contains(array $array, $searchElement, int $fromIndex = null): bool

invoke

Calls the method named by methodName on each value in the list. Any extra arguments passed to invoke will be forwarded on to the method invocation.

Parameters
Syntax
 invoke(array $array, mixed $iteratee, ...$args): array
Example
<?php
$res = Arrays::invoke([[5, 1, 7], [3, 2, 1]], [Arrays::class, "sort"]);
// [ [1, 5, 7], [1, 2, 3] ]

pluck

A convenient version of what is perhaps the most common use-case for map: extracting a list of property values.

Parameters
Syntax
 pluck(array $array, mixed $key): array
Example
<?php
 $res = Arrays::pluck([
      ["name" => "moe",   "age" =>  40],
      ["name" => "larry", "age" =>  50],
      ["name" => "curly", "age" =>  60],
  ], "name"); // ["moe, "larry", "curly" ]

max

Returns the maximum value in list. If an iteratee function is provided

Parameters
Syntax
 max(array $array, mixed $iteratee = null, $context = null)
Example
<?php
$res = Arrays::max([1,2,3]); // 3

$res = Arrays::max([
        ["name" => "moe",   "age" =>  40],
        ["name" => "larry", "age" =>  50],
        ["name" => "curly", "age" =>  60],
    ], function($stooge){
     return $stooge["age"];
    });
// ["name" => "curly", "age" =>  60]

min

Returns the minimum value in list. If an iteratee function is provided

Parameters
Syntax
 min(array $array, mixed $iteratee = null, $context = null)
Example
<?php
$res = Arrays::min([1,2,3]); // 1

$res = Arrays::min([
        ["name" => "moe",   "age" =>  40],
        ["name" => "larry", "age" =>  50],
        ["name" => "curly", "age" =>  60],
    ], function($stooge){
     return $stooge["age"];
    });
// ["name" => "moe",   "age" =>  40]

sortBy

Return a (stably) sorted copy of list, ranked in ascending order by the results of running each value through iteratee. iteratee may also be the mixed name of the property to sort by

Parameters
Syntax
 sortBy(array $array, $iteratee, $context = null): array
Example
<?php
$res = Arrays::sortBy([1, 2, 3, 4, 5, 6], function($a){
    return \sin($a);
}); // [5, 4, 6, 3, 1, 2]

$res = Arrays::sortBy([
    ["name" => "moe",   "age" =>  40],
    ["name" => "larry", "age" =>  50],
    ["name" => "curly", "age" =>  60],
], "name");
// [["name" => "curly", "age" =>  60],...]

groupBy

Split a collection into sets, grouped by the result of running each value through iterator

Parameters
Syntax
 groupBy(array $array, $iteratee, $context = null): array
Example
<?php
$res = Arrays::groupBy([1.3, 2.1, 2.4], function($num) { return floor($num); });
// [1 => [ 1.3 ], 2 => [ 2.1, 2.4 ]]

indexBy

Given a list, and an iteratee function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.

Parameters
Syntax
 indexBy(array $array,  $iteratee, $context = null): array
Example
<?php

$res = Arrays::indexBy([
    ["name" => "moe",   "age" =>  40],
    ["name" => "larry", "age" =>  50],
    ["name" => "curly", "age" =>  60],
], "name");
// [ 40 => ["name" => "moe",   "age" =>  40], ...]

countBy

Sort a list into groups and return a count for the number of objects in each group.

Parameters
Syntax
 countBy(array $array,  $iteratee, $context = null): array
Example
<?php
$res = Arrays::countBy([1, 2, 3, 4, 5], function($num) {
    return $num % 2 == 0 ? "even": "odd";
});
// [ "odd => 3, "even" => 2 ]

shuffle

Return a shuffled copy of the list

Parameters
Syntax
 shuffle(array $array): array
Example
<?php
$res = Arrays::shuffle([1, 2, 3]); // [ 2, 1, 3 ]

sample

Produce a random sample from the list. Pass a number to return n random elements from the list. Otherwise a single random item will be returned.

Parameters
Syntax
 sample(array $array, int $count = null)
Example
<?php
$res = Arrays::sample([1, 2, 3], 3); // [ 2, 1, 3 ]

toArray

Creates a real Array from the list

Parameters
Syntax
 toArray($collection): array

size

Return the number of values in the list.

Parameters
Syntax
 size(array $array): int
Example
<?php
$res = Arrays::size([
    "one" => 1,
    "two" => 2,
    "three" => 3
]); // 3

partition

split array into two arrays: one whose elements all satisfy predicate and one whose elements all do not satisfy predicate.

Parameters
Syntax
 partition(array $array, mixed $mixed): array
Example
<?php
$res = Arrays::partition([0, 1, 2, 3, 4, 5], function($val) {
    return $val % 2;
}); //  [[1, 3, 5], [0, 2, 4]]

Underscore.js\Arrays methods

first

Get the first value from an array regardless index order and without modifying the array When passed in array has no element, it returns undefined, unless $defaultValue is supplied. Then it returns $defaultValue (when $defaultValue is a mixed then the result of its execution)

Parameters
Syntax
 first(array $array, $defaultValue = null)
Example
<?php
$element = Arrays::first([1, 2, 3]);
$element = Arrays::first($arr, 1);
$element = Arrays::first($arr, function(){ return 1; });

initial

Returns everything but the last entry of the array. Especially useful on the arguments object. Pass count to exclude the last count elements from the result.

Parameters
Syntax
 initial(array $array, int $count = 1): array
Example
<?php
$res = Arrays::initial([5, 4, 3, 2, 1]); // [5, 4, 3, 2]
//...
$res = Arrays::initial([5, 4, 3, 2, 1], 3); // [5, 4]

last

Get the last value from an array regardless index order and without modifying the array

Parameters
Syntax
 last(array $array): mixed
Example
<?php
$element = Arrays::last([1, 2, 3]);

rest

Returns the rest of the elements in an array. Pass an index to return the values of the array from that index onward.

Parameters
Syntax
 rest(array $array, int $count = 1): array
Example
<?php
$res = Arrays::rest([5, 4, 3, 2, 1]); // [4, 3, 2, 1]
//...
$res = Arrays::rest([5, 4, 3, 2, 1], 3); // [2, 1]

compact

Returns a copy of the array with all falsy values removed.

Parameters
Syntax
 compact(array $array): array
Example
<?php
$res = Arrays::compact([0, 1, false, 2, '', 3]); // [1, 2, 3]

flatten

Flattens a nested array (the nesting can be to any depth). If you pass shallow, the array will only be flattened a single level.

Parameters
Syntax
 flatten(array $array, bool $shallow = false): array
Example
<?php
$res = Arrays::flatten([1, [2], [3, [[4]]]]); // [1, 2, 3, 4]
//...
$res = Arrays::flatten([1, [2], [3, [[4]]]], true); // [1, 2, 3, [[4]]]

without

Returns a copy of the array with all instances of the values removed.

Parameters
Syntax
 without(array $array, ...$values): array
Example
<?php
$res = Arrays::without([1, 2, 1, 0, 3, 1, 4], 0, 1); // [2, 3, 4]

union

Computes the union of the passed-in arrays: the list of unique items, in order, that are present in one or more of the arrays.

Parameters
Syntax
 union(...$args): array
Example
<?php
$res = Arrays::union(
    [1, 2, 3],
    [101, 2, 1, 10],
    [2, 1]
); // [1, 2, 3, 101, 10]

intersection

Computes the list of values that are the intersection of all the arrays. Each value in the result is present in each of the arrays.

Parameters
Syntax
 intersection(array $array, ...$sources): array
Example
<?php
$res = Arrays::intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); // [1, 2]

$res = Arrays::intersection(
    ["a" => "green", "b" => "brown", "c" => "blue", "red"],
    ["a" => "green", "b" => "yellow", "blue", "red"]
); // [ "a" => "green" ]

difference

Returns the values from array that are not present in the other arrays.

Parameters
Syntax
 difference(array $array, ...$sources): array
Example
<?php
$res = Arrays::difference([ 1, 2, 3, 4, 5], [5, 2, 10]); // [1, 3, 4]

$res = Arrays::difference(
    ["a" => "green", "b" => "brown", "c" => "blue", "red"],
    ["a" => "green", "yellow", "red"]
);
// [ "b" => "brown", "c" => "blue",  "red" ]

uniq

Produces a duplicate-free version of the array

Parameters
Syntax
 uniq(array $array): array
Example
<?php
$res = Arrays::uniq([1,2,3,1,1,2]); // [1,2,3]

zip

Merges together the values of each of the arrays with the values at the corresponding position. Useful when you have separate data sources that are coordinated through matching array indexes.

Parameters
Syntax
 zip(array $array, ...$sources): array
Example
<?php
$res = Arrays::zip(
  ["moe", "larry", "curly"],
  [30, 40, 50],
  [true, false, false]
); //  [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]

unzip

The opposite of zip. Given an array of arrays, returns a series of new arrays, the first of which contains all of the first elements in the input arrays, the second of which contains all of the second elements, and so on.

Parameters
Syntax
 unzip(array $array): array
Example
<?php
$res = Arrays::unzip([["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]);
//  [["moe", "larry", "curly"], [30, 40, 50], [true, false, false]]

object

Converts arrays into objects. Pass either a single list of [key, value] pairs, or a list of keys, and a list of values. If duplicate keys exist, the last value wins.

Parameters
Syntax
 object(array $array, array $values = null): PlainObject
Example #1
$obj = Arrays::object([ "foo" =>
            [
                "bar" => [
                    "baz" => "BAZ"
                ]
            ]
        ]);
echo $obj->foo->bar->baz; // BAZ
Example #2
$obj = Arrays::object([["moe", 30], ["larry", 40], ["curly", 50]]);
echo $obj->moe; // 30
echo $obj->larry; // 40
echo $obj->curly; // 50
Example #3
$obj = Arrays::object(["moe", "larry", "curly"], [30, 40, 50]);
echo $obj->moe; // 30
echo $obj->larry; // 40
echo $obj->curly; // 50

sortedIndex

Uses a binary search to determine the index at which the value should be inserted into the list in order to maintain the list's sorted order. If an iteratee function is provided, it will be used to compute the sort ranking of each value, including the value you pass. The iteratee may also be the mixed name of the property to sort by

Parameters
Syntax
 sortedIndex(array $array, $value, $iteratee = null, $context = null): int
Example #1
<?php
$res = Arrays::sortedIndex([10, 20, 30, 40, 50], 35); // 3
Example #2
<?php
$stooges = [
    ["name" => "moe",   "age" =>  40],
    ["name" => "larry", "age" =>  50],
    ["name" => "curly", "age" =>  60],
];
$res = Arrays::sortedIndex($stooges, ["name" => "larry", "age" => 50], "age"); // 1

findIndex

Find index of the first element matching the condition in $mixed

Parameters
Syntax
 findIndex(array $array, $iteratee = null, $context = null): int
Example
<?php
$inx = Arrays::findIndex([
            ["val" => "FOO"],
            ["val" => "BAR"],
        ], function ($item){
            return $item["val"] === "BAR";
        }); // 1

findLastIndex

Like findIndex but iterates the array in reverse, returning the index closest to the end where the predicate truth test passes.

Parameters
Syntax
 findLastIndex(array $array, $iteratee = null, $context = null): int
Example
<?php
$src = [
    [
        'id' => 1,
        'name' => 'Ted',
        'last' => 'White',
    ],
    [
        'id' => 2,
        'name' => 'Bob',
        'last' => 'Brown',
    ],
    [
        'id' => 3,
        'name' => 'Ted',
        'last' => 'Jones',
    ],
];

$res = Arrays::findLastIndex($src, [ "name" => "Ted" ]); // 2

range

A function to create flexibly-numbered lists of integers, handy for each and map loops. start, if omitted, defaults to 0; step defaults to 1. Returns a list of integers from start (inclusive) to stop (exclusive), incremented (or decremented) by step, exclusive. Note that ranges that stop before they start are considered to be zero-length instead of negative — if you'd like a negative range, use a negative step.

Parameters
Syntax
 range(int $start, int $end = null, int $step = 1): array
Example #1
<?php
$res = Arrays::range(10); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Example #2
<?php
$res = Arrays::range(1, 11); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Example #3
<?php
$res = Arrays::range(0, 30, 5); // [0, 5, 10, 15, 20, 25]
Example #4
<?php
$res = Arrays::range(0, -10, -1);
// [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]

Underscore.js\Chaining methods

chain

Returns a wrapped object. Calling methods on this object will continue to return wrapped objects until value is called.

Parameters
Syntax
 chain($array): Arrays
Example
<?php
$res = Arrays::chain([1, 2, 3])
    ->map(function($num){ return $num + 1; })
    ->filter(function($num){ return $num > 1; })
    ->reduce(function($carry, $num){ return $carry + $num; }, 0)
    ->value();

Underscore.js\Objects methods

allKeys

Retrieve all the names of object's own and inherited properties. Given we consider here JavaScript object as associative array, it is an alias of [keys](#keys]

Parameters
Syntax
 allKeys(array $array): array

mapObject

Like map, but for associative arrays. Transform the value of each property in turn.

Parameters
Syntax
 mapObject(array $array, callable $iteratee, $context = null): array
Example
<?php
$res = Arrays::mapObject([
    "start" => 5,
    "end" => 12,
], function($val){
    return $val + 5;
}); // [ "start" => 10, "end" => 17, ]

pairs

Convert an object into a list of [key, value] pairs. Alias of entries

Parameters
Syntax
 pairs(array $array): array
Example
<?php
$res = Arrays::pairs(["foo" => "FOO", "bar" => "BAR"]); // [["foo", "FOO"], ["bar", "BAR"]]

invert

Returns a copy of the object where the keys have become the values and the values the keys. For this to work, all of your object's values should be unique and string serializable.

Parameters
Syntax
 invert(array $array): array
Example
<?php
$res = Arrays::invert([
    "Moe" => "Moses",
    "Larry" => "Louis",
    "Curly" => "Jerome",
]);
// [
//    "Moses" => "Moe",
//    "Louis" => "Larry",
//    "Jerome" => "Curly",
// ]

findKey

Similar to findIndex, but for keys in objects. Returns the key where the predicate truth test passes or undefined

Parameters
Syntax
 findKey(array $array, $iteratee = null, $context = null): string
Example
<?php
$src = [
    "foo" => [
        'name' => 'Ted',
        'last' => 'White',
    ],
    "bar" => [
        'name' => 'Frank',
        'last' => 'James',
    ],
    "baz" => [
        'name' => 'Ted',
        'last' => 'Jones',
    ],
];
$res = Arrays::findKey($src, [ "name" => "Ted" ]); // foo

extend

Shallowly copy all of the properties in the source objects over to the destination object, and return the destination object. Any nested objects or arrays will be copied by reference Given we consider here JavaScript object as associative array, it's an alias of assign

Parameters
Syntax
 extend(... $arrays): array
Example
<?php
$res = Arrays::extend(["foo" => 1, "bar" => 2], ["bar" => 3], ["foo" => 4], ["baz" => 5]);
// ["foo" => 4, "bar" => 3, "baz" => 5]

pick

Return a copy of the object, filtered to only have values for the whitelisted keys (or array of valid keys). Alternatively accepts a predicate indicating which keys to pick.

Parameters
Syntax
 pick(array $array, ...$keys): array
Example #1
<?php
$res = Arrays::pick([
    'name' => 'moe',
    'age' => 50,
    'userid' => 'moe1',
  ], 'name', 'age');
// ['name' => 'moe', 'age' => 50, ]
Example #2
<?php
$res = Arrays::pick([
    'name' => 'moe',
    'age' => 50,
    'userid' => 'moe1',
], function($value){
    return is_int($value);
});
// ['age' => 50 ]

omit

Return a copy of the object, filtered to omit the blacklisted keys (or array of keys). Alternatively accepts a predicate indicating which keys to omit.

Parameters
Syntax
 omit(array $array, ...$keys): array
Example #1
<?php
$res = Arrays::omit([
    'name' => 'moe',
    'age' => 50,
    'userid' => 'moe1',
  ], 'userid');
// ['name' => 'moe', 'age' => 50, ]
Example #2
<?php
$res = Arrays::omit([
    'name' => 'moe',
    'age' => 50,
    'userid' => 'moe1',
], function($value){
    return is_int($value);
});
// ['name' => 'moe', 'userid' => 'moe1', ]

defaults

Fill in undefined properties in object with the first value present in the following list of defaults objects.

Parameters
Syntax
 defaults(array $array, array $defaults): array
Example
<?php
$res = Arrays::defaults([
    "flavor" => "chocolate"
 ], [
     "flavor" => "vanilla",
     "sprinkles" => "lots",
 ]); //["flavor" => "chocolate", "sprinkles" => "lots", ]

has

Does the object contain the given key? Identical to object.hasOwnProperty(key), but uses a safe reference to the hasOwnProperty function, in case it's been overridden accidentally.

Parameters
Syntax
 has(array $array, string $key): bool
Example
<?php
$res = Arrays::has([
     "flavor" => "vanilla",
     "sprinkles" => "lots",
 ], "flavor"); // true

property

Returns a function that will itself return the key property of any passed-in object.

Parameters
Syntax
 property(string $prop): callable
Example
<?php
$stooge = [ "name" => "moe" ];
$res = Arrays::property("name")($stooge); // "moe"

propertyOf

Inverse of property. Takes an object and returns a function which will return the value of a provided property.

Parameters
Syntax
 propertyOf(array $array): callable
Example
<?php
$stooge = [ "name" => "moe" ];
$res = Arrays::propertyOf($stooge)("name"); // "moe"

matcher

Returns a predicate function that will tell you if a passed in object contains all of the key/value properties present in attrs.

Parameters
Syntax
 matcher(array $attrs): callable
Example
<?php
$src = [
    [
        "foo" => "FOO",
        "bar" => "BAR",
    ],
    [
        "bar" => "BAR",
        "baz" => "BAZ",
    ]
];
$matcher = Arrays::matcher([
        "foo" => "FOO",
        "bar" => "BAR",
]);
$res = Arrays::filter($src, $matcher);
// [[ "foo" => "FOO", "bar" => "BAR", ]]

isEmpty

Returns true if an enumerable object contains no values (no enumerable own-properties).

Parameters
Syntax
 isEmpty(array $array): bool
Example
<?php
  $res = Arrays::isEmpty([]); // true

isEqual

Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.

Parameters
Syntax
 isEqual(array $array, array $target): bool
Example
<?php
$res = Arrays::isEqual([
        "name" => "moe",
        "luckyNumbers" => [13, 27, 34],
        ], [
        "name" => "moe",
        "luckyNumbers" => [13, 27, 34],
]); // true

isMatch

Tells you if the keys and values in properties are contained in object.

Parameters
Syntax
 isMatch(array $array, array $attrs): bool
Example
<?php
 $res = Arrays::isMatch([
        "foo" => "FOO",
        "bar" => "BAR",
        "baz" => "BAZ",
    ],
    [
        "foo" => "BAZ",
    ]); // false

isArray

Returns true if source is an array.

Parameters
Syntax
 isArray(array $array): bool
Example
<?php
   $res = Arrays::isArray([ 1, 2, 3 ]); // true

isObject

Returns true if value is an Object. Given we consider here JavaScript object as associative array, it is an alias of isAssocArray

Parameters
Syntax
 isObject($source): bool
Example
<?php
   $res = Arrays::isObject([ "foo" => 1, "bar" => 1, ]); // true

Other methods

replace

Replace (similar to MYSQL REPLACE statement) an element matching the condition in predicate function with the value If no match found, add the value to the end of array

Parameters
Syntax
 replace(array $array, mixed $mixed, $element): array
Example
<?php
$array = Arrays::replace([
            ["val" => "FOO"],
            ["val" => "BAR"],
        ], function ($item){
            return $item["val"] === "BAR";
        }, ["val" => "BAZ"]);

isAssocArray

Test whether array is not sequential, but associative array

Parameters
Syntax
 isAssocArray(array $array): bool
Example
<?php
$bool = Arrays::isAssocArray([1, 2, 3]); // false

Dsheiko\Extras\Collections

Following types iterable, ArrayObject, Iterator belong to collections. Array extras like ::map, ::reduce do not make sense on a live collection, one can rather convert the collection to an array (::toArray) and then apply array extras.

chain

Returns a wrapped object. Calling methods on this object will continue to return wrapped objects until value is called.

Parameters
Syntax
 chain({iterable|ArrayObject|Iterator} $collection)
Example
<?php
$res = $res = Collections::chain(new \ArrayObject([1,2,3]))
            ->toArray()
            ->value();
echo $res; // "534"

each

Iterate over a list of elements, yielding each in turn to an $callable function

Parameters
Syntax
each($collection, callable $callable)
Example
<?php
$sum = 0;
$obj = new \ArrayObject([1,2,3]);
Collections::each($obj->getIterator(), function ($i) use (&$sum){
    $sum += $i;
});

toArray

Convert collectionb to an array

Parameters
Syntax
toArray($collection)
Example
<?php
$sum = 0;
$obj = new \ArrayObject([1,2,3]);
$res = Collections::toArray();

Dsheiko\Extras\Functions

Method _.defer is not relevant in in the context of PHP

JavaScript-inspired methods

apply

Calls a function with a given this value, and arguments provided as an array

Parameters
Syntax
apply(mixed $source, $context = null, array $args = [])
Example
<?php
$obj = Arrays::object(["foo" => "FOO"]);
$source = function( $input ){ return $input . "_" . $this->foo; };
$res = Functions::apply($source, $obj, ["BAR"]); // "BAR_FOO"

bind

Creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called

Parameters
Syntax
bind(mixed $source, $context = null)
Example
<?php
$obj = Arrays::object(["foo" => "FOO"]);
$source = function( $input ){ return $input . "_" . $this->foo; };
$func = Functions::bind($source, $obj);
echo $func("BAR"); // "BAR_FOO"

call

Calls a function with a given $context value and arguments provided individually.

Parameters
Syntax
call(mixed $source, $context = null, ...$args)
Example
<?php
$obj = Arrays::object(["foo" => "FOO"]);
$source = function( $input ){ return $input . "_" . $this->foo; };
$res = Functions::call($source, $obj, "BAR"); // "BAR_FOO"

toString

Returns a mixed representing the source code of the function.

Parameters
Syntax
toString(mixed $source)
Example
<?php
echo Functions::toString("strlen");
mixed(112) "Function [ <internal:Core> function strlen ] {

  - Parameters [1] {
    Parameter #0 [ <required> $str ]
  }
}

Underscore.js-inspired methods

bindAll

Binds a number of methods on the object, specified by $methodNames, to be run in the context of that object whenever they are invoked. Very handy for binding functions that are going to be used as event handlers, which would otherwise be invoked with a fairly useless this. $methodNames are required

Parameters
Syntax
 bindAll($obj, ...$methodNames)
Example
<?php
$foo = (object)[
    "value" => 1,
    "increment" => function(){
        $this->value++;
    },
    "reset" => function(){
        $this->value = 0;
    }
];
Functions::bindAll($foo, "increment", "reset");

($foo->increment)();
echo $foo->value; // 2

($foo->reset)();
echo $foo->value; // 0

partial

Partially apply a function by filling in any number of its arguments

Parameters
Syntax
 partial(mixed $source, ...$boundArgs)
Example
<?php
$subtract = function($a, $b) { return $b - $a; };
$sub5 = Functions::partial($subtract, 5);
$res = $sub5(20); // 15

memoize

Memoizes a given function by caching the computed result. Useful for speeding up slow-running computations. If passed an optional hashFunction

Parameters
Syntax
memoize($source, $hasher = null)
Example
<?php
$counter = Functions::memoize("fixtureCounter::increment");
$counter($foo); // 1
$counter($foo); // 1
$counter($bar); // 2
$counter($baz); // 3

delay

Much like setTimeout, invokes function after wait milliseconds. If you pass the optional arguments, they will be forwarded on to the function when it is invoked.

Parameters
Syntax
 delay(mixed $source, int $wait, ...$args)
Example
<?php
$counter = Functions::memoize("fixtureCounter::increment");
$counter($foo); // 1
$counter($foo); // 1
$counter($bar); // 2
$counter($baz); // 3

throttle

Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with.

Parameters
Syntax
 throttle(mixed $source, int $wait)
Example
<?php
function increment()
{
    static $count = 0;
    return ++$count;
}
$func = Functions::throttle("increment", 20);
$func(); // 1
$func(); // false
usleep(20000);
$func();  // 2
$func();  // false

debounce

Creates and returns a new debounced version of the passed function which will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked

Parameters
Syntax
 debounce(mixed $source, int $wait)
Example
<?php
function increment()
{
    static $count = 0;
    return ++$count;
}
$func = Functions::debounce("increment", 20);
$func(); // false
$func(); // false
usleep(20000);
$func();  // 1
$func();  // false

once

Creates a version of the function that can only be called one time. Repeated calls to the modified function will have no effect, returning the value from the original call. Useful for initialization functions, instead of having to set a boolean flag and then check it later.

Parameters
Syntax
 once(mixed $source)
Example
<?php
function increment()
{
    static $count = 0;
    return ++$count;
}
$func = Functions::once("increment");
$func(); // 1
$func(); // 1
$func(); // 1

after

Creates a version of the function that will only be run after being called count times. Useful for grouping asynchronous responses, where you want to be sure that all the async calls have finished, before proceeding.

Parameters
Syntax
 after(mixed $source, int $count)
Example
<?php
function increment()
{
    static $count = 0;
    return ++$count;
}
$func = Functions::after("increment", 2);
$func(); // false
$func(); // false
$func(); // 1

before

Creates a version of the function that can be called no more than count times. The result of the last function call is memoized and returned when count has been reached.

Parameters
Syntax
 before(mixed $source, int $count)
Example
<?php
function increment()
{
    static $count = 0;
    return ++$count;
}
$func = Functions::before("increment", 2);
$func(); // 1
$func(); // 2
$func(); // 2

wrap

Wraps the first function inside of the wrapper function, passing it as the first argument. This allows the transforming function to execute code before and after the function runs, adjust the arguments, and execute it conditionally.

Parameters
Syntax
 wrap(mixed $source, mixed $transformer)
Example
<?php
function increment()
{
    static $count = 0;
    return ++$count;
}
$func = Functions::wrap("increment", function($func){
    return 10 + $func();
});
$func(); // 11

negate

Returns a new negated version of the predicate function.

Parameters
Syntax
negate(mixed $source)
Example
<?php
$func = Functions::negate(function(){ return false; });
$func(): // true

compose

Returns the composition of a list of functions, where each function consumes the return value of the function that follows. In math terms, composing the functions f(), g(), and h() produces f(g(h())).

Parameters
Syntax
 compose(...$functions)
Example
<?php
$greet = function(mixed $name){ return "hi: " . $name; };
$exclaim = function(mixed $statement){ return strtoupper($statement) . "!"; };
$welcome = Functions::compose($greet, $exclaim);
$welcome("moe"); // "hi: MOE!"

times

Invokes the given iteratee function n times. Each invocation of iteratee is called with an index argument. Produces an array of the returned values.

Parameters
Syntax
 times(callable $source, int $n = 1, $context = null)
Example
<?php
$counter = 0;
Functions::times(function($value) use(&$counter){
    $counter += $value;
}, 5); // 15

chain

Returns a wrapped object. Calling methods on this object will continue to return wrapped objects until value is called.

Parameters
Syntax
 chain(mixed $value): Functions
Example
<?php
$res = Strings::chain( " 12345 " )
            ->replace("/1/", "5")
            ->replace("/2/", "5")
            ->trim()
            ->substr(1, 3)
            ->value();
echo $res; // "534"

Dsheiko\Extras\Strings

Overview example

<?php
$res = Strings::from( " 12345 " )
            ->replace("/1/", "5")
            ->replace("/2/", "5")
            ->trim()
            ->substr(1, 3)
            ->get();
echo $res; // "534"

charAt

Return a new string consisting of the single UTF-16 code unit located at the specified offset into the string.

Parameters
Syntax
 charAt(string $value, int $index = 0): string
Example
<?php
$res = Strings::charAt("ABC", 1); // "B"

charCodeAt

Return an integer between 0 and 65535 representing the UTF-16 code unit at the given index

Parameters
Syntax
 charCodeAt(string $value, int $index = 0): int
Example
<?php
$res = Strings::charCodeAt("ABC", 0); // 65

concat

Concatenate the string arguments to the calling string and returns a new string.

Parameters
Syntax
 concat(string $value, ...$strings): string
Example
<?php
$res = Strings::concat("AB", "CD", "EF"); // ABCDEF

endsWith

Determine whether a string ends with the characters of a specified string, returning true or false as appropriate.

Parameters
Syntax
 endsWith(string $value, string $search): bool
Example
<?php
$res = Strings::endsWith("12345", "45"); // true

fromCharCode

Return a string created from the specified sequence of code units.

Parameters
Syntax
 fromCharCode(...$codes): string
Example
<?php
$res = Strings::fromCharCode(65, 66, 67); // ABC

includes

Parameters
Syntax
 includes(string $value, string $search, int $position = 0): bool
Example
<?php
$res = Strings::includes("12345", "1"); // true

indexOf

Return the index of the first occurrence of the specified value

Parameters
Syntax
 indexOf(string $value, string $searchStr, int $fromIndex = 0): int
Example
<?php
$res = Strings::indexOf("ABCD", "BC"); // 1
$res = Strings::indexOf("ABCABC", "BC", 3); // 4

lastIndexOf

Return the index of the last occurrence of the specified value

Parameters
Syntax
 lastIndexOf(string $value, string $searchStr, int $fromIndex = 0): int
Example
<?php
$res = Strings::lastIndexOf("canal", "a"); // 3
$res = Strings::lastIndexOf("canal", "a", 2); // 1

localeCompare

Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order

Parameters
Syntax
 localeCompare(string $value, string $compareStr): int
Example
<?php
\setlocale (LC_COLLATE, 'de_DE');
$res = Strings::localeCompare("a", "c"); // -2

match

Retrieves the matches when matching a string against a regular expression.

Parameters
Syntax
 match(string $value, string $regexp): null|array
Example
<?php
$res = Strings::match("A1B1C1", "/[A-Z]/"); // ["A", "B", "C"]

padEnd

Pad the current string (to right) with a given string (repeated, if needed) so that the resulting string reaches a given length

Parameters
Syntax
 padEnd(string $value, int $length, string $padString = " "): string
Example
<?php
$res = Strings::padEnd("abc", 10); // "abc       "
$res = Strings::padEnd("abc", 10, "foo"); // "abcfoofoof"

padStart

Pad the current string (to left) with a given string (repeated, if needed) so that the resulting string reaches a given length

Parameters
Syntax
 padStart(string $value, int $length, string $padString = " "): string
Example
<?php
$res = Strings::padStart("abc", 10); // "       abc"
$res = Strings::padStart("abc", 10, "foo"); // "foofoofabc"

remove

Remove substring from the string

Parameters
Syntax
 remove(string $value, string $search): string
Example
<?php
$res = Strings::remove("12345", "1"); // "2345"

repeat

Construct and return a new string which contains the specified number of copies of the string on which it was called, concatenated together.

Parameters
Syntax
 repeat(string $value, int $count): string
Example
<?php
$res = Strings::repeat("abc", 2); // abcabc

replace

Perform a regular expression search and replace

Parameters
Syntax
 replace(string $value, string $pattern, string $replacement): string
Example
<?php
$res = Strings::replace("12345", "/\d/s", "*"); // "*****"

slice

Extract a section of a string and returns it as a new string.

Parameters
Syntax
 slice(string $value, int $beginIndex, int $endIndex = null): string

See also Difference between slice and substring

Example
<?php
$res = Strings::slice("The morning is upon us.", 1, 8); // "he morn"

split

Splits a string into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.

Parameters
Syntax
 split(string $value, string $delimiter): array
Example
<?php
$res = Strings::split("a,b,c", ","); // ["a", "b", "c"]

startsWith

Determine whether a string begins with the characters of a specified string, returning true or false as appropriate.

Parameters
Syntax
 startsWith(string $value, string $search): bools
Example
<?php
$res = Strings::startsWith("12345", "12"); // true

substr

Return part of a string

Parameters
Syntax
 substr(string $value, int $start, int $length = null): string
Example
<?php
$res = Strings::substr("12345", 1, 3); // "234"

substring

Return the part of the string between the start and end indexes, or to the end of the string.

Parameters
Syntax
 substring(string $value, int $beginIndex, int $endIndex = null): string

See also Difference between slice and substring

Example
<?php
$value = "Mozilla";
$res = Strings::substring($value, 0, 1); // "M"
$res = Strings::substring($value, 1, 0); // "M"

toLowerCase

Return the calling string value converted to lower case.

Parameters
Syntax
 toLowerCase(string $value): string
Example
<?php
$res = Strings::toLowerCase("AbC"); // abc

toUpperCase

Return the calling string value converted to upper case.

Parameters
Syntax
 toUpperCase(string $value): string
Example
<?php
$res = Strings::toUpperCase("AbC"); // ABC

trim

Strip whitespace (or other characters) from the beginning and end of a string

Parameters
Syntax
 trim(string $value, string $mask = " \t\n\r\0\x0B"): string
Example
<?php
$res = Strings::trim("  12345   "); // "12345"

escape

Escapes a string for insertion into HTML

Parameters
Syntax
 escape(string $string): string
Example
<?php
$res = Strings::escape("Curly, Larry & Moe"); // "Curly, Larry &amp; Moe"

unescape

The opposite of escape

Parameters
Syntax
 unescape(string $string): string
Example
<?php
$res = Strings::unescape("Curly, Larry &amp; Moe"); // "Curly, Larry & Moe"

chain

Returns a wrapped object. Calling methods on this object will continue to return wrapped objects until value is called.

Parameters
Syntax
 chain(string $value): Strings
Example
<?php
$res = Strings::chain( " 12345 " )
            ->replace("/1/", "5")
            ->replace("/2/", "5")
            ->trim()
            ->substr(1, 3)
            ->value();
echo $res; // "534"

Dsheiko\Extras\Numbers

JavaScript-inspired methods

isFinite

Determines whether the passed value is a finite number.

Parameters
Syntax
 isFinite($source): bool
Example
<?php
$res = Numbers::isFinite(log(0)); // true

isInteger

Determines whether the passed value is an integer.

Parameters
Syntax
 isInteger($source): bool
Example
<?php
$res = Numbers::isInteger(123); // true

isNaN

Determines whether the passed value is Not a Number.

Parameters
Syntax
 isNaN($source): bool
Example
<?php
$res = Numbers::isNaN(\NAN); // true

parseFloat

Parse source to a float

Parameters
Syntax
 parseFloat($source)
Example #1
<?php
$src = "4.567abcdefgh";
echo Numbers::isNaN(Numbers::parseFloat($src)); // true
Example #2
<?php
$src = "abcdefgh";
echo Numbers::isNaN(Numbers::parseFloat($src)); // false

parseInt

Parse source to an integer

Parameters
Syntax
 isInteger($source): bool
Example #1
<?php
$res = Numbers::parseInt("123"); // 123
Example #2
<?php
$res = Numbers::parseInt("0xF", 16); // 15
Example #3
<?php
$res = Numbers::parseInt("101110", 2); // 46
Example #4
<?php
$res = Numbers::parseInt("0xF", 2); // NaN

toFixed

Formats a number using fixed-point notation

Parameters
Syntax
 toFixed(float $value, int $digits = 0): float
Example #1
<?php
$res = Numbers::toFixed(12345.6789, 1); // 12345.7
Example #2
<?php
$res = Numbers::toFixed(12345.6789, 6); // 12345.678900

toPrecision

Returns a string representing the Number object to the specified precision.

Parameters
Syntax
 toPrecision(float $value, int $precision = null): float
Example #1
<?php
$res = Numbers::toPrecision(5.123456); // 5.123456
Example #2
<?php
$res = Numbers::toPrecision(5.123456, 5); // 5.1235
Example #3
<?php
$res = Numbers::toPrecision(5.123456, 2); // 5.1
Example #4
<?php
$res = Numbers::toPrecision(5.123456, 1); // 5

Underscore.js-inspired methods

isNumber

Determines whether the passed value is a number.

Parameters
Syntax
 isNumber($source): bool
Example #1
<?php
$res = Numbers::isNumber(1); // true
Example #2
<?php
$res = Numbers::isNumber(1.1); // true

chain

Returns a wrapped object. Calling methods on this object will continue to return wrapped objects until value is called.

Parameters
Syntax
 chain($value)

Dsheiko\Extras\Booleans

Underscore.js-inspired methods

isBoolean

Determines whether the passed value is a boolean.

Parameters
Syntax
 isBoolean($source): bool
Example
<?php
$res = Numbers::isBoolean(true); // true

chain

Returns a wrapped object. Calling methods on this object will continue to return wrapped objects until value is called.

Parameters
Syntax
 chain($value)

Dsheiko\Extras\Type\PlainObject

Object representing an associative array similar to plain object in JavaScript

Overview example

<?php
use Dsheiko\Extras\Type\PlainObject;

$po = new PlainObject(["foo" => "FOO", "bar" => "BAR"]);
// $po = \Dsheiko\Extras\Array::object(["foo" => "FOO", "bar" => "BAR"]);
echo $po->foo; // "FOO"
echo $po->bar; // "BAR"

JavaScript-inspired methods

assign

Copy the values of all properties from one or more source arrays to a target array.

Parameters
Syntax
 assign(PlainObject $target, ...$sources): PlainObject
Example
<?php
$po1 = new PlainObject(["foo" => "FOO"]);
$po2 = new PlainObject(["bar" => "BAR"]);
$res = PlainObject::assign($po1, $po2);
echo $res->foo; // "FOO"
echo $res->bar; // "BAR"
echo $po1->foo; // "FOO"
echo $po1->bar; // "BAR"

entries

Return an array of a given object's own enumerable property [key, value] pairs

Syntax
 entries(): array
Example
<?php
$po = new PlainObject(["foo" => "FOO", "bar" => "BAR"]);
$res = $po->entries();
var_dump($res[0]); // ["foo", "FOO"]
var_dump($res[1]); // ["bar", "BAR"]

keys

Return all the keys or a subset of the keys of a plain object

Parameters
Syntax
 keys($searchValue = null): array
Example
<?php
$po = new PlainObject(["foo" => "FOO", "bar" => "BAR"]);
$res = $po->keys(); // ["foo", "bar"]

toArray

Transform back to array

Syntax
 toArray(): array
Example
<?php
$po = new PlainObject(["foo" => "FOO", "bar" => "BAR"]);
$res = $po->toArray();
echo is_array($res); // true

values

Return all the values of a plain object

Syntax
 values(): array
Example
<?php
$po = new PlainObject(["foo" => "FOO", "bar" => "BAR"]);
$res = $po->values(); // ["FOO", "BAR"]

Underscore.js\Objects methods

mapObject

Like map, but for associative arrays. Transform the value of each property in turn.

Parameters
Syntax
 mapObject(callable $iteratee, $context = null): PlainObject
Example
<?php
$po = new PlainObject([
        "start" => 5,
        "end" => 12,
]);
$res = $po->mapObject(function($val){
    return $val + 5;
}); // PlainObject{ "start": 10, "end": 17 }

pairs

Convert an object into a list of [key, value] pairs. Alias of entries

Syntax
 pairs(): array
Example
<?php
$po = new PlainObject(["foo" => "FOO", "bar" => "BAR"]);
$res = $po->pairs(); // [["foo", "FOO"], ["bar", "BAR"]]

invert

Returns a copy of the object where the keys have become the values and the values the keys. For this to work, all of your object's values should be unique and string serializable.

Syntax
 invert(): PlainObject
Example
<?php
$po = new PlainObject([
    "Moe" => "Moses",
    "Larry" => "Louis",
    "Curly" => "Jerome",
]);
$res = $po->invert();
echo $res->Moses; // "Moe"
echo $res->Louis; // "Larry"
echo $res->Jerome; // "Curly"

findKey

Similar to findIndex, but for keys in objects. Returns the key where the predicate truth test passes or undefined

Parameters
Syntax
 findKey($iteratee = null, $context = null): string
Example
<?php
$po = new PlainObject([
    "foo" => [
        'name' => 'Ted',
        'last' => 'White',
    ],
    "bar" => [
        'name' => 'Frank',
        'last' => 'James',
    ],
    "baz" => [
        'name' => 'Ted',
        'last' => 'Jones',
    ],
]);
$res = $po->findKey([ "name" => "Ted" ]); // "foo"

pick

Return a copy of the object, filtered to only have values for the whitelisted keys (or array of valid keys). Alternatively accepts a predicate indicating which keys to pick.

Parameters
Syntax
 pick(...$keys): PlainObject
Example #1
<?php
$po = new PlainObject([
    'name' => 'moe',
    'age' => 50,
    'userid' => 'moe1',
]);
$res = $po->pick('name', 'age');
// PlainObject{ 'name': 'moe', 'age': 50 }
Example #2
<?php
$po = new PlainObject([
    'name' => 'moe',
    'age' => 50,
    'userid' => 'moe1',
]);

$res = $po->pick(function($value){
    return is_int($value);
});
// PlainObject{ 'age': 50 }

omit

Return a copy of the object, filtered to omit the blacklisted keys (or array of keys). Alternatively accepts a predicate indicating which keys to omit.

Parameters
Syntax
 omit(...$keys): PlainObject
Example #1
<?php
$po = new PlainObject([
    'name' => 'moe',
    'age' => 50,
    'userid' => 'moe1',
]);

$res = $po->omit('userid');
// PlainObject{ 'name': 'moe', 'age': 50 }
Example #2
<?php
$po = new PlainObject([
    'name' => 'moe',
    'age' => 50,
    'userid' => 'moe1',
]);

$res = $po->omit(function($value){
    return is_int($value);
});
// PlainObject{ 'name': 'moe', 'userid': 'moe1' }

defaults

Fill in undefined properties in object with the first value present in the following list of defaults objects.

Parameters
Syntax
 defaults(array $defaults): PlainObject
Example
<?php
$po = new PlainObject([
    "flavor" => "chocolate"
]);
$res = $po->defaults([
     "flavor" => "vanilla",
     "sprinkles" => "lots",
]);
// PlainObject{ "flavor": "chocolate", "sprinkles": "lots" }

has

Does the object contain the given key? Identical to object.hasOwnProperty(key), but uses a safe reference to the hasOwnProperty function, in case it's been overridden accidentally.

Parameters
Syntax
 has(string $key): bool
Example
<?php
$po = new PlainObject([
     "flavor" => "vanilla",
     "sprinkles" => "lots",
]);
$res = $po->has("flavor"); // true

isEmpty

Returns true if an enumerable object contains no values (no enumerable own-properties).

Syntax
 isEmpty(): bool
Example
<?php
$po = new PlainObject([]);

$res = Arrays::isEmpty($po); // true

Any extras

Overview example

<?php
use \Dsheiko\Extras\Any;

$res = Any::chain(new \ArrayObject([1,2,3]))
    ->toArray() // value is [1,2,3]
    ->map(function($num){ return [ "num" => $num ]; })
    // value is [[ "num" => 1, ..]]
    ->reduce(function($carry, $arr){
        $carry .= $arr["num"];
        return $carry;

    }, "") // value is "123"
    ->replace("/2/", "") // value is "13"
    ->then(function($value){
      if (empty($value)) {
        throw new \Exception("Empty value");
      }
      return $value;
    })
    ->value();
echo $res; // "13"

isDate

Returns true if source is an instance of DateTime.

Parameters
Syntax
 isDate($source): bool
Example
<?php
$res = Any::isDate(new DateTime('2011-01-01T15:03:01.012345Z')); // true

isError

Returns true if source is an Error

Parameters
Syntax
 isError($source): bool
Example
<?php
try {
    throw new Error("message");
} catch (\Error $ex) {
    $res = Any::isError($ex); // true
}

isException

Returns true if source is an Exception

Parameters
Syntax
 isException($source): bool
Example
<?php
try {
    throw new Error("message");
} catch (\Exception $ex) {
    $res = Any::isException($ex); // true
}

isNull

Returns true if source is NULL

Parameters
Syntax
 isNull($source): bool
Example
<?php
Any::isNull(null); // true

chain

Returns a wrapped object. Calling methods on this object will continue to return wrapped objects until value is called.

Parameters
Syntax
 chain(string $value)

Chaining

chain

Iterate over a list of elements, yielding each in turn to an $callable function

Parameters
Syntax
{Set}::chain($target): Chain
Example #1
<?php
use Dsheiko\Extras\Chain;

// Chain of calls
$res = Chain::chain([1, 2, 3]) // same as Arrays::chain([1, 2, 3])
    ->map(function($num){ return $num + 1; })
    ->filter(function($num){ return $num > 1; })
    ->reduce(function($carry, $num){ return $carry + $num; }, 0)
    ->value(); // 9
Example #2
<?php
use Dsheiko\Extras\Chain;

class MapObject
{
    public $foo = "FOO";
    public $bar = "BAR";
}

$res = Chain::chain(new MapObject)
  ->keys()
  ->value(); // ["foo", "bar"]

then

Binds a then (transformer) function to the chain

Parameters
Syntax
{Set}::then($function): Chain
Example
<?php
use Dsheiko\Extras\Chain;

$res = Chain::chain(new \ArrayObject([1,2,3))
        // same as Collections::chain(new \ArrayObject([1,2,3])
        ->toArray()
        ->then("json_encode")
        ->value(); // "[1,2,3]"

tap

Underscore syntax for then

Parameters
Syntax
{Set}::tap($function): Chain

value

Extracts the value of a wrapped object.

#

Syntax
$chain::value()

Dsheiko\Extras\Utils

Methods _.noConflict, _.mixin and _.template are not relevant in the context of PHP

Methods _.escape and _.unescape belong to Dsheiko\Extras\Strings

Method _.times belongs to Dsheiko\Extras\Functions

identity

Returns the same value that is used as the argument. In math: f(x) = x This function looks useless, but is used throughout Underscore as a default iteratee.

Syntax
 identity(): callable
Example
<?php
$res = Utils::identity();
$res(42); // 42

constant

Creates a function that returns the same value that is used as the argument of the method

Parameters
Syntax
 constant($value): callable
Example
<?php
$res = Utils::constant(42);
$res(1, 2, 3); // 42

noop

Returns null irrespective of the arguments passed to it. Useful as the default for optional callback arguments.

Parameters
Syntax
 noop(...$args)
Example
<?php
$res = Utils::noop(1,2,3); // null

random

Returns a random integer between min and max, inclusive. If you only pass one argument, it will return a number between 0 and that number

Parameters
Syntax
 random(int $min , int $max = null)
Example
<?php
$res = Utils::random(100); // 42
$res = Utils::random(5, 10); // 7

iteratee

Generates a callback that can be applied to each element in a collection.

Parameters
Syntax
 iteratee($value, $context = null): callable
Example #1
<?php
// return identity() for null
$res = Utils::iteratee(null);
$res(1); // 1
Example #2
<?php
// return matcher() for an array
$macther = Utils::iteratee(["foo" => "FOO"]);
$res = Arrays::find([["foo" => "FOO"]], $macther); // ["foo" => "FOO"]
Example #3
<?php
// return normalized callablefor a callable
$res = Utils::iteratee(function(){ return 42; });
$res(); // 42
Example #4
<?php
// bind callable for a context
$obj = (object)["value" => 42];
$res = Utils::iteratee(function(){ return $this->value; }, $obj);
$res(); // 42
Example #5
<?php
// return property() for other types
$res = Utils::iteratee("foo");
$res(["foo" => "FOO"]); // "FOO"

uniqueId

Generate a globally-unique id for client-side models or DOM elements that need one. If prefix is passed, the id will be appended to it.

Parameters
Syntax
 uniqueId(string $prefix = null): string
Example #1
<?php
$res = Utils::uniqueId(); // "5acb4ab426fc9"
Example #2
<?php
$res = Utils::uniqueId("contact_"); // "contact_5acb4ab427262"

result

If the value of the named property is a function then invoke it with the object as context; otherwise, return it. If a default value is provided and the property doesn't exist or is undefined then the default will be returned. If defaultValue is a function its result will be returned.

Parameters
Syntax
 result(array $array, string $prop)
Example
<?php
$options = [
    "foo" => "FOO",
    "bar" => function() {
        return "BAR";
    },
];
echo Utils::result($options, "foo"); // "FOO"
echo Utils::result($options, "bar"); // "BAR"

now

Returns an integer timestamp for the current time

Syntax
 now(): int
Example
<?php
echo Utils::now(); // 1392066795351