PHP code example of ihor / nspl

1. Go to this page and download the library: Download ihor/nspl library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ihor / nspl example snippets


// get user ids
$userIds = map(propertyGetter('id'), $users);

// or sort them by age
$sortedByAge = sorted($users, methodCaller('getAge'));

// or check if they all are online
$online = all($users, methodCaller('isOnline'));

// or define new function as composition of the existing ones
$flatMap = compose(rpartial(flatten, 1), map);

// get user ids
$userIds = array_map(function($user) { return $user->id; }, $users);

// sort them by age, note that the following code modifies the original users array
usort($users, function($user1, $user2) {
    return $user1->getAge() - $user2->getAge();
});

// check if they all are online
$online = true;
foreach ($users as $user) {
    if (!$user->isOnline()) {
        $online = false;
        break;
    }
}

// define new function as composition of the existing ones
$flatMap = function($function, $list) {
    // note the inconsistency in array_map and array_reduce parameters
    return array_reduce(array_map($function, $list), 'array_merge', []);
};



use function nspl\a\zip;
$pairs = zip([1, 2, 3], ['a', 'b', 'c']);

use nspl\a;
$pairs = a\zip([1, 2, 3], ['a', 'b', 'c']);

assert(1 === id(1));

assert([1, 3, 5, 7, 9] === apply('range', [1, 10, 2]));

$sum = function($a, $b) { return $a + $b; };
$inc = partial($sum, 1);

$cube = rpartial('pow', 3);

$oddNumbers = ppartial('range', array(0 => 1, 2 => 2));

use const \nspl\a\flatten;
use const \nspl\a\map;
use function \nspl\f\compose;
use function \nspl\f\partial;
use function \nspl\f\rpartial;

$flatMap = compose(rpartial(flatten, 1), map);
assert(['hello', 'world', 'foo', 'bar'] === $flatMap(partial('explode', ' '), ['hello world', 'foo bar']));

use const \nspl\op\sum;
use const \nspl\a\filter;
use const \nspl\a\map;
use const \nspl\a\reduce;
use function \nspl\f\partial;

$isEven = function($x) { return $x % 2 === 0; };
$square = function($x) { return $x * $x; };

// sum of squares of all even numbers less than 20
$sum = pipe(
    range(1, 20),
    partial(filter, $isEven),
    partial(map, $square),
    partial(reduce, sum)
);

> use function \nspl\a\with;
>
> $sum = with(range(1, 20))
>    ->filter($isEven)
>    ->map($square)
>    ->reduce(sum);
> 

$f = function($arg) {
    echo sprintf("Performing heavy calculations with '%s'\n", $arg);
    return $arg;
};

$memoized = memoized($f);
echo $memoized('Hello world!') . "\n";
echo $memoized('Hello world!') . "\n";

$f = function() {
    echo "Invoked\n";
};

$throttled = throttled($f, 10);

$startedAt = microtime(true);
do {
    $throttled();
} while((microtime(true) - $startedAt) * 1000 < 30); // 30ms

use const \nspl\a\map;
use const \nspl\a\filter;

$incListItems = partial(map, function($v) { return $v + 1; });
$filterNumbers = partial(filter, 'is_numeric');

use const nspl\op\sum;
use function nspl\a\reduce;

assert(6 === reduce(sum, [1, 2, 3]));

use function nspl\op\itemGetter;
use function nspl\a\map;

assert([2, 5, 8] === map(itemGetter(1), [[1, 2, 3], [4, 5, 6], [7, 8, 9]]));

$userIds = map(propertyGetter('id'), $users);

$userIds = map(methodCaller('getId'), $users);

$users = map(instanceCreator(User::class), $usersData);

assert(true === all([true, true, true]));

assert(true === any([true, false, false]));

assert(['A', 'B', 'C'] === map('strtoupper', ['a', 'b', 'c']));

$duplicate = function($v) { return [$v, $v]; }
assert(['hello', 'hello', 'world', 'world'] === flatMap($duplicate, ['hello', 'world']));

assert([[1, 'a'], [2, 'b'], [3, 'c']] === zip([1, 2, 3], ['a', 'b', 'c']));

use const \nspl\op\sum;

assert([101, 1002, 10003] === zipWith(sum, [1, 2, 3], [100, 1000, 10000]));

assert(6 === reduce(function($a, $b) { return $a + $b; }, [1, 2, 3]));

// Which is the same as
use const \nspl\op\sum;
assert(6 === reduce(sum, [1, 2, 3]));


assert([1, 2, 3] === filter('is_numeric', ['a', 1, 'b', 2, 'c', 3]));

assert(['a', 'b', 'c'] === filterNot('is_numeric', ['a', 1, 'b', 2, 'c', 3]));

assert([1, 3, 5] === take([1, 2, 3, 4, 5, 6, 7, 8, 9], 3, 2));

assert(array('hello' => 1, 'world' => 2) === takeKeys(array('hello' => 1, 'world' => 2, 'foo' => 3), ['hello', 'world']));

assert([1, 2, 3] === takeWhile('is_numeric', [1, 2, 3, 'a', 'b', 'c', 4, 5, 6]));

assert(1 === first([1, 2, 3, 4, 5, 6, 7, 8, 9]));

assert(2 === second([1, 2, 3, 4, 5, 6, 7, 8, 9]));

assert([7, 8, 9] === drop([1, 2, 3, 4, 5, 6, 7, 8, 9], 6));

assert(array('hello' => 1, 'world' => 2) === dropKeys(array('hello' => 1, 'world' => 2, 'foo' => 3), ['foo']));

assert(['a', 'b', 'c', 4, 5, 6] === dropWhile('is_numeric', [1, 2, 3, 'a', 'b', 'c', 4, 5, 6]));

assert(9 === last([1, 2, 3, 4, 5, 6, 7, 8, 9]));

assert([[1, 2, 3], ['a', 'b', 'c']] === partition('is_numeric', ['a', 1, 'b', 2, 'c', 3]));

assert([[1], ['a', 2, 'b', 3, 'c']] === span('is_numeric', [1, 'a', 2, 'b', 3, 'c']));

$indexedById = indexed([
    array('id' => 1, 'name' => 'John'),
    array('id' => 2, 'name' => 'Kate'),
    array('id' => 3, 'name' => 'Robert'),
], 'id');

assert([1, 2, 3] === sorted([2, 3, 1]));
assert(['c', 'b', 'a'] === sorted(['c', 'a', 'b'], true));

$usersSortedByName = sorted($users, function($u) { return $u->getName(); });

// Which is the same as
use function \nspl\op\methodCaller;
$usersSortedByName = sorted($users, methodCaller('getName'));

assert(array('a' => 1, 'b' => 2, 'c' => 3) === keySorted(array('b' => 2, 'c' => 3, 'a' => 1));

assert([1, 2, 3, 4, 5, 6, 7, 8, 9] === flatten([[1, [2, [3]]], [[[4, 5, 6]]], 7, 8, [9]]));
assert([1, 2, [3], [4, 5, 6], 7, 8, 9] === flatten([[1, [2, [3]]], [[[4, 5, 6]]], 7, 8, [9]], 2));

assert([['a', 'hello'], ['b', 'world'], ['c', 42]] === pairs(array('a' => 'hello', 'b' => 'world', 'c' => 42)));

assert([1, 2, 3, 4, 5, 6] === merge([1, 2, 3], [4, 5, 6]));

assert([2, 0, 1] === reorder([0, 1, 2], 2, 0)); // move item from the 2nd position to the begining of the list

$data = array('a' => 1, 'b' => 2, 'c' => 3);
assert(2 === value($data, 'b', -1));
assert(-1 === value($data, 'd', -1));

assert([1, 2, 3] === values(array('a' => 1, 'b' => 2, 'c' => 3)));

assert(['a', 'b', 'c'] === keys(array('a' => 1, 'b' => 2, 'c' => 3)));

assert(true === in(1, [1, 2, 3]);

assert([1] === diff([1, 2, 3], new ArrayObject([2, 3, 4]));

assert([2, 3] === intersect([1, 2, 3], new ArrayObject([2, 3, 4]));

assert([
    [1, 'a'],
    [1, 'b'],
    [2, 'a'],
    [2, 'b'],
], cartesianProduct([1, 2], ['a', 'b']));

assert([
    array('hello' => 1, 'world' => 'a'),
    array('hello' => 1, 'world' => 'b'),
    array('hello' => 2, 'world' => 'a'),
    array('hello' => 2, 'world' => 'b'),
], cartesianProduct(array('hello' => [1, 2], 'world' => ['a', 'b'])));

use function nspl\op\sum;

$square = function($n) { return $n * $n; };

$isEven = function($n) { return $n % 2 === 0; };

$sum = with(range(1, 5))
  ->filter($isEven)
  ->map($square)
  ->reduce(sum);

assert(20 === $sum);

use const \nspl\a\first;
assert([1, 2, 3] === map(first, [[1, 'a'], [2, 'b'], [3, 'c']]));

// Calls generator function and logs the yielded values
function logged(callable $generatorFunction)
{
    static $count = 1;
    return function(...$args) use ($generatorFunction, &$count) {
        foreach ($generatorFunction(...$args) as $value) {
            echo $count++ . '. ' .  (string) $generatorFunction . ' -> ' . $value . "\n";
            yield $value;
        };
    };
}

function naturalNumbers()
{
    $current = 1;
    while (true) yield $current++;
}
const naturalNumbers = 'naturalNumbers';

// Returns square of a number
function square($n)
{
    return $n * $n;
}
const square = 'square';

// Checks if a number is even
function isEven($n)
{
    return $n % 2 === 0;
}
const isEven = 'isEven';

use const nspl\a\lazy\{take, map, filter};

$map = logged(map);
$take = logged(take);
$filter = logged(filter);
$numbers = logged(naturalNumbers)();

$evenNumbers = $filter(isEven, $numbers); // filter only even numbers
$firstThreeEvenNumbers = $take($evenNumbers, 3); // take only first 3 even numbers
$result = $map(square, $firstThreeEvenNumbers); // and calculate their squares

foreach ($result as $value) {
    echo "\nNext value is $value \n\n";
}

$result = with(naturalNumbers())
    ->filter(isEven)
    ->take(3)
    ->map(square);

use const \nspl\args\int;
use const \nspl\args\string;
use const \nspl\args\arrayAccess;
use function \nspl\args\expects;

function nth($sequence, $n)
{
    expects([arrayAccess, string], $sequence);
    expects(int, $n);

    return $sequence[$n];
}

nth('hello world', 'blah');

use const \nspl\args\numeric;
use function \nspl\args\expects;

function sum($x, $y)
{
    expectsAll(numeric, [$x, $y]);

    return $x + $y;
}

function splitBy($string, $separator = ' ', $limit = null)
{
    expectsAll(string, [$string, $separator]);
    expectsOptional(int, $limit);

    return explode($separator, $string, $limit);
}

function setUsername($username)
{
    expects([string, longerThan(3), shorterThan(10)], $username);
    // ...
}

function setState($state)
{
    expects(values('running', 'idle', 'stopped'), $state);
    // ...
}

class Service
{
    // ...
    public function setCache($cache)
    {
        expects(withMethods('set', 'get'), $cache);
        $this->cache = $cache;
    }
    // ....
}

function even($value)
{
    return is_int($value) && $value %2 === 0;
}

function half($number)
{
    expects('even', $number);
    return $number / 2;
}

const even = 'even';

function half($number)
{
    expects(even, $number);
    return $number / 2;
}

half('pie');

$a = array();
foreach([1, 2, 1, 1, 3, 3, 3] as $v) {
    if (!isset($a[$v])) {
        $a[$v] = 0;
    }
    ++$a[$v];
}

$a = defaultarray(0);
foreach([1, 2, 1, 1, 3, 3, 3] as $v) {
    ++$a[$v];
}

$set = set(1, 2);

$set->add('hello');
$set[] = 'world';

$set->delete('hello');

$array = [1, 2, 3];
$intersection = $set->intersection($array);

$anotherSet = Set::fromArray([1, 2, 3]);
$difference = $set->difference($anotherSet);

$iterator = new \ArrayIterator([1, 2, 3]);
$union = $set->union($iterator);

$isSubset = $set->isSubset([1, 2, 'hello', 'world']);

$isSuperset = $set->isSuperset([1, 2]);

use function \nspl\rnd\weightedChoice;
use function \nspl\a\pairs;

$nextPet = weightedChoice([['cat', 20], ['hamster', 30], ['dog', 50]]);
$nextFavouriteColor = weightedChoice(pairs(array(
    'red' => 0.2,
    'green' => 0.3,
    'blue' => 0.5,
)));
autoload.php
$input
$key
$key
$key
$arg
$arg
__invoke($value)