-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.php
71 lines (61 loc) · 1.56 KB
/
common.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
declare(strict_types=1);
/**
* Read a file and return each row as an array, skipping empty lines and trimming new lines
*
* @param string $filename
* @return array|bool
*/
function readRows(string $filename): array
{
return file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
}
/**
* Read a file and return the while content as a string
*
* @param string $filename
* @return string
*/
function readFileContent(string $filename): string
{
return trim(file_get_contents($filename));
}
/**
* Cast each element in an array to int
*
* @param array $array
* @return array|int[]
*/
function toIntArray(array $array): array
{
return array_map(fn (string $value): int => (int)$value, $array);
}
/**
* @param float $startTime
*/
function printExecutionInfo(float $startTime): void
{
$peak = formatBytes(memory_get_peak_usage());
$duration = microtime(true) - $startTime;
$duration = number_format($duration, 4);
echo PHP_EOL;
echo "Peaked at $peak memory usage and took $duration seconds to execute" . PHP_EOL;
}
/**
* @see https://stackoverflow.com/a/2510459/779652
* @param $bytes
* @param int $precision
* @return string
*/
function formatBytes($bytes, $precision = 2)
{
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= (1 << (10 * $pow));
return round($bytes, $precision) . ' ' . $units[$pow];
}
function transpose($array): array {
return array_map(null, ...$array);
}