Skip to content

Commit d24d70e

Browse files
committed
add subtract curry function implement dynamic chain
1 parent fd7e081 commit d24d70e

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
This problem was asked by **Squarespace**.
2+
3+
Write a function, add_subtract, which alternately adds and subtracts curried arguments. Here are some sample operations:
4+
5+
```java
6+
add_subtract(7) -> 7
7+
8+
add_subtract(1)(2)(3) -> 1 + 2 - 3 -> 0
9+
10+
add_subtract(-5)(10)(3)(9) -> -5 + 10 - 3 + 9 -> 11
11+
```
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
function add_subtract(n) {
2+
let acc = n;
3+
let op = true;
4+
5+
return function inner(m) {
6+
if (!m) {
7+
return acc;
8+
}
9+
acc += op ? m : -m;
10+
op = !op;
11+
return inner;
12+
};
13+
}
14+
15+
console.log(add_subtract(7)()); // Output: 7
16+
console.log(add_subtract(1)(2)(3)()); // Output: 0
17+
console.log(add_subtract(-5)(10)(3)(9)()); // Output: 11
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
def add_subtract(n):
2+
acc = n
3+
op = True
4+
def inner(m=None):
5+
nonlocal acc
6+
nonlocal op
7+
if m is None:
8+
return acc
9+
if op:
10+
acc += m
11+
else:
12+
acc -= m
13+
op = not op
14+
return inner
15+
return inner
16+
17+
# Examples
18+
print(add_subtract(7)()) # Output: 7
19+
print(add_subtract(1)(2)(3)()) # Output: 0
20+
print(add_subtract(-5)(10)(3)(9)()) # Output: 11

0 commit comments

Comments
 (0)