Skip to content

Commit

Permalink
Added A::zipObj() and O::assoc()
Browse files Browse the repository at this point in the history
  • Loading branch information
meszaros-lajos-gyorgy committed Apr 13, 2021
1 parent 66c9da2 commit da8646d
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ Every method is abide to the following rules ( or at least they should. if they
- **join** -
- **pickRandom** - selects a random item from the given array
- **concat** - concatenates every argument into an array. if any of the arguments are arrays, then those will get unnested
- **zipObj** -

### String

Expand Down Expand Up @@ -148,6 +149,16 @@ Every method is abide to the following rules ( or at least they should. if they

- **pick** -

- **assoc** - assigns value to an object via a given key. already existing keys will get overwritten

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

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

## Future plans

I keep adding methods as I come across the need for them, so if you're missing a method you'd use, then 1) PRs are welcome, 2) Issues are welcome.
Expand Down
14 changes: 14 additions & 0 deletions src/A.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Shovel;

use stdClass;

class A
{
// A::of(1, 2, 3) -> [1, 2, 3]
Expand Down Expand Up @@ -307,4 +309,16 @@ public static function concat(...$args) {
return self::ensureArray($arg);
},$args));
}

// A::zipObj(['a', 'b'], [1, 2]) -> {a:1, b:2}
public static function zipObj(array $keys, array $values): object {
$_keys = self::uniq(self::concat(self::keys($keys), self::keys($values)));
$_keys = self::filter(function($key) use ($keys, $values) {
return array_key_exists($key, $keys) && array_key_exists($key, $values);
}, $_keys);

return self::reduce(function($result, $key) use ($keys, $values) {
return O::assoc($keys[$key], $values[$key], $result);
}, new stdClass(), $_keys);
}
}
10 changes: 9 additions & 1 deletion src/O.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Shovel;

use stdClass;

class O
{
// O::isObject(new stdClass()) -> true
Expand Down Expand Up @@ -37,8 +39,14 @@ function ($result, $key) use ($data) {
}
return $result;
},
new \stdClass(),
new stdClass(),
$keys
);
}

// O::assoc('foo', 'bar', {}) -> {foo: 'bar'}
public static function assoc(string $key, $value, object $data): object {
$data->{$key} = $value;
return $data;
}
}

0 comments on commit da8646d

Please sign in to comment.