Repository navigation
Expand file tree
/
Copy pathglobal_functions.php
More file actions
127 lines (109 loc) · 2.43 KB
/
Copy pathglobal_functions.php
File metadata and controls
127 lines (109 loc) · 2.43 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
<?php
/**
* This file exists because functions in namespaces are a world of hurt.
* Some functions deserve a place as globals, when they're consistent with the inbuilt php functions.
* Prefer Static methods when it makes sense.
*
* Functions should be sorted alphabetically.
*
* Maths deserve a place as global.
* Array manipulation too.
*/
/**
* Pushes $value into $array only if $value is not already in it.
* This is merely a convenience wrapper for the `in_array` check.
*
* @param array $array
* @param mixed $value
*/
function array_push_once (&$array, $value)
{
if (!in_array($value, $array)) {
$array[] = $value;
}
}
/**
* Rotates passed array $offset times to the left, like a cycle would.
* You can only use this with numerically-indexed arrays.
* Note that it mutates the provided array.
*
* Eg:
* $a = array(7,8,9);
* array_rotate_left($a,1); // array(8,9,7)
*
* @param array $array The array to rotate
* @param int $offset When negative, rotates to the right
* @throws \Exception
*/
function array_rotate_left (&$array, $offset=0) {
for (reset($array); is_int(key($array)); next($array));
if (!is_null(key($array))) {
throw new Exception("Can only rotate numeric arrays");
}
$l = count($array);
$offset = ( $l + ($offset % $l) ) % $l;
while ($offset--) {
$first = array_shift($array);
$array[] = $first;
}
}
/**
* Obvious
* We all wrote that line at some point.
* (Ongoing Poll: 1/1 = 100%)
*
* @param $value
* @param $min
* @param $max
* @return mixed
*/
function boundarize ($value, $min, $max)
{
return min($max, max($min, $value));
}
/**
* Is $n an even number ?
* Is it even a number ? ^.^
*
* @param $n
* @return bool
* @throws Exception
*/
function even($n)
{
if (!is_integer($n)) throw new Exception((string)$n." is not an integer");
return $n % 2 === 0;
}
/**
* Is $n an odd number ?
* The odd Zero is even !
*
* @param $n
* @return bool
*/
function odd($n)
{
return !even($n);
}
/**
* Returns +1 for a positive $number,
* -1 for a negative $number,
* 0 for 0.
*
* Throws on unsupported $number.
*
* @param number $number
* @return int
* @throws Exception
*/
function norm ($number)
{
if ($number === 0) {
return 0;
} else if ($number > 0) {
return 1;
} else if ($number < 0) {
return -1;
}
throw new Exception("Unsupported number $number");
}