Completed
Pull Request — master (#4)
by Siwapun
05:55 queued 04:27
created

curryN()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.6
c 0
b 0
f 0
cc 3
nc 1
nop 2
1
<?php
2
namespace Aerophant\Ramda;
3
4
/**
5
 * @param int $a
6
 * @param int $b
7
 * @return int
8
 */
9
function add()
10
{
11
  $add = function (int $a, int $b) {
12
    return $a + $b;
13
  };
14
  $arguments = func_get_args();
15
  $curried = curryN($add, 2);
16
  return call_user_func_array($curried, $arguments);
17
}
18
19
/**
20
 * @param mixed $data
21
 * @return \Closure
22
 */
23
function always()
24
{
25
  $always = function ($data) {
26
    return function () use ($data) {
27
      return $data;
28
    };
29
  };
30
  $arguments = func_get_args();
31
  $curried = curryN($always, 1);
32
  return call_user_func_array($curried, $arguments);
33
}
34
35
/**
36
 * @return callable
37
 * @throws \Exception
38
 */
39
function compose()
40
{
41
  $arguments = array_reverse(func_get_args());
42
  return call_user_func_array('Aerophant\Ramda\pipe', $arguments);
43
}
44
45
/**
46
 * @param string $class
47
 * @return \Closure
48
 */
49
function construct()
50
{
51
  $construct = function ($class) {
52
    return function () use ($class) {
53
      return new $class();
54
    };
55
  };
56
  $arguments = func_get_args();
57
  $curried = curryN($construct, 1);
58
  return call_user_func_array($curried, $arguments);
59
}
60
61
function curryN(callable $fn, int $numberOfArguments)
62
{
63
  return function () use ($fn, $numberOfArguments) {
64
    $arguments = func_get_args();
65
    $length = count($arguments);
66
    if ($length > $numberOfArguments) {
67
      throw new \InvalidArgumentException(
68
        "Number of passed($length) parameters is greater than expected($numberOfArguments)"
69
      );
70
    }
71
    // NO CURRY
72
    if ($length == $numberOfArguments) {
73
      return call_user_func_array($fn, $arguments);
74
    }
75
    // AUTO CURRY
76
    $curriedFn = function () use ($fn, $arguments) {
77
      $curriedArguments = func_get_args();
78
      return call_user_func_array($fn, array_merge($arguments, $curriedArguments));
79
    };
80
    return curryN($curriedFn, $numberOfArguments - $length);
81
  };
82
}
83
84
/**
85
 * @return callable
86
 * @throws \Exception
87
 */
88
function pipe()
89
{
90
  $arguments = func_get_args();
91
  $length = count($arguments);
92
  if ($length === 0) {
93
    throw new \Exception("pipe requires at least one argument");
94
  }
95
  return function () use ($arguments) {
96
    $internalArguments = func_get_args();
97
    $initialValue = call_user_func_array($arguments[0], $internalArguments);
98
    $accumulator = function ($acc, $it) {
99
      return call_user_func_array($it, [$acc]);
100
    };
101
    return array_reduce(drop(0, $arguments), $accumulator, $initialValue);
102
  };
103
}
104