diff --git a/README.md b/README.md index c1b5694..7067a15 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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. diff --git a/src/A.php b/src/A.php index accf739..054367a 100644 --- a/src/A.php +++ b/src/A.php @@ -2,6 +2,8 @@ namespace Shovel; +use stdClass; + class A { // A::of(1, 2, 3) -> [1, 2, 3] @@ -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); + } } diff --git a/src/O.php b/src/O.php index 8d49408..27a9b6b 100644 --- a/src/O.php +++ b/src/O.php @@ -2,6 +2,8 @@ namespace Shovel; +use stdClass; + class O { // O::isObject(new stdClass()) -> true @@ -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; + } }