Skip to content

Commit 60b44f2

Browse files
committed
feat: add keys(), values(), invert(), pick(), omit()
1 parent a662f66 commit 60b44f2

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

src/UnderscoreBase.php

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,83 @@ public function now()
251251
return \microtime(1) * 1000;
252252
}
253253

254+
/**
255+
* Get all the keys.
256+
*
257+
* @return self
258+
*/
259+
public function keys()
260+
{
261+
return new static(\array_keys($this->data));
262+
}
263+
264+
/**
265+
* Get all the keys.
266+
*
267+
* @return self
268+
*/
269+
public function values()
270+
{
271+
return new static(\array_values($this->data));
272+
}
273+
274+
/**
275+
* Pair all items to use an array of index and value.
276+
*
277+
* @return self
278+
*/
279+
public function pairs()
280+
{
281+
$pairs = [];
282+
283+
foreach ($this->data as $index => $value) {
284+
$pairs[$index] = [$index, $value];
285+
}
286+
287+
return new static($pairs);
288+
}
289+
290+
/**
291+
* Swap index and value of all the items. The values should be stringifiable.
292+
*
293+
* @return self
294+
*/
295+
public function invert()
296+
{
297+
return new static(\array_flip($this->data));
298+
}
299+
300+
/**
301+
* Pick only the items having one of the whitelisted indexes.
302+
*
303+
* @param array|...string|...int $index Either whitelisted indexes as array or as variads.
304+
*
305+
* @return self
306+
*/
307+
public function pick($index)
308+
{
309+
$indices = \array_flip(\is_array($index) ? $index : \func_get_args());
310+
311+
return new static(\array_intersect_key($this->data, $indices));
312+
}
313+
314+
/**
315+
* Omit the items having one of the blacklisted indexes.
316+
*
317+
* @param array|...string|...int $index Either blacklisted indexes as array or as variads.
318+
*
319+
* @return self
320+
*/
321+
public function omit($index)
322+
{
323+
$indices = \array_diff(
324+
\array_keys($this->data),
325+
\is_array($index) ? $index : \func_get_args()
326+
);
327+
328+
return $this->pick($indices);
329+
}
330+
254331
/**
255332
* A static shortcut to constructor.
256333
*

0 commit comments

Comments
 (0)