meszaros-lajos-gyorgy / shovel

A PHP library for manipulating Arrays, Strings and Objects - inspired by ramda.js
0 stars 0 forks source link

Test every function for immutability #4

Open meszaros-lajos-gyorgy opened 3 years ago

meszaros-lajos-gyorgy commented 3 years ago

All functions need to be double checked to see if they are in fact really immutable and if not, then they should be updated. This might be a good place to add unit tests.

For example the following code is NOT immutable:

<?php
$point2d = new stdClass();
$point2d->x = 10;
$point2d->y = 20;

$point3d = O::assoc('z', 30, $point2d);

echo '<pre>';
var_dump($point2d);

// $point2d also contains "z"
meszaros-lajos-gyorgy commented 3 years ago

Normal arrays are immutable

$a = [1, 2, 3];

function xxxx($x) {
    $x[0] = 10;
    return $x;
}

$b = xxxx($a);

var_dump($a);
echo '<br />';
var_dump($b);

// $a[0] == 1, $b[0] == 10

Changing array size is also immutable:

<?php

$a = [1, 2, 3];

function xxxx($x) {
    $x[] = 10;
    return $x;
}

$b = xxxx($a);

var_dump($a);
echo '<br />';
var_dump($b);

// count($a) == 3, count($b) == 4
meszaros-lajos-gyorgy commented 3 years ago

Associative arrays are also immutable

$a = ['a' => 1, 'b' => 2, 'c' => 3];

function xxxx($x) {
    $x['a'] = 10;
    return $x;
}

$b = xxxx($a);

var_dump($a);
echo '<br />';
var_dump($b);

// $a['a'] = 1, $b['a'] = 10
meszaros-lajos-gyorgy commented 3 years ago

https://www.simonholywell.com/post/2017/04/php-and-immutability-part-three/