Skip to content

Commit

Permalink
Added associative array support for O::assoc and O::dissoc
Browse files Browse the repository at this point in the history
  • Loading branch information
meszaros-lajos-gyorgy committed Jul 25, 2021
1 parent 7004381 commit 4814774
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -881,6 +881,17 @@ $point2d->y = 20;
$point3d = O::assoc("z", 30, $point2d); // {"x": 10, "y": 20, "z": 30}
```

```php
$point2d = [
"x" => 10,
"y" => 20
];

$point3d = O::assoc("z", 30, $point2d); // ["x" => 10, "y" => 20, "z" => 30]
```

**Does not work on arrays with numeric keys!**

</details>

<details>
Expand All @@ -897,6 +908,18 @@ $point3d->z = 30;
$point2d = O::dissoc("z", 30, $point3d); // {"x": 10, "y": 20}
```

```php
$point3d = [
"x" => 10,
"y" => 20,
"z" => 30
];

$point2d = O::dissoc("z", 30, $point3d); // ["x" => 10, "y" => 30]
```

**Does not work on arrays with numeric keys!**

</details>

<details>
Expand Down
16 changes: 12 additions & 4 deletions src/O.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,22 @@ function ($result, $key) use ($data) {
}

// O::assoc('foo', 'bar', {}) -> {foo: 'bar'}
public static function assoc(string $key, $value, object $data): object {
$data->{$key} = $value;
public static function assoc(string $key, $value, $data): object {
if (O::isObject($data)) {
$data->{$key} = $value;
} elseif(A::isArray($data) && A::isAssoc($data)) {
$data[$key] = $value;
}
return $data;
}

// O::dissoc('foo', {foo: 'bar', fizz: 'buzz'}) -> {fizz: 'buzz'}
public static function dissoc(string $key, object $data): object {
unset($data->{$key});
public static function dissoc(string $key, $data): object {
if (O::isObject($data)) {
unset($data->{$key});
} elseif(A::isArray($data) && A::isAssoc($data)) {
unset($data[$key]);
}
return $data;
}

Expand Down

0 comments on commit 4814774

Please sign in to comment.