<!DOCTYPE html>
<html>
<head>
<meta name="description" content="chaining function composition">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script id="jsbin-javascript">
"use strict";
var elevator = {
floor: 5,
up: function up() {
this.floor += 1;
return this;
},
down: function down() {
this.floor -= 1;
return this;
}
};
var newFloor = elevator.up().up().down().up().floor;
console.log(newFloor);
//////////
var elevator2 = {
floor: 5
};
var up = function up(elevator) {
return {
floor: elevator.floor + 1
};
};
var down = function down(elevator) {
return {
floor: elevator.floor - 1
};
};
var newFloor2 = up(down(up(up(elevator2)))).floor;
console.log(newFloor2);
///////////
var sequence2 = function sequence2(f1, f2) {
return function () {
return f2(f1.apply(undefined, arguments));
};
};
var sequence = function sequence(f1) {
for (var _len = arguments.length, fRest = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
fRest[_key - 1] = arguments[_key];
}
return fRest.reduce(sequence2, f1);
};
var move = sequence(up, up, down, up);
var newElevator = move(elevator);
console.log(newElevator.floor);
</script>
<script id="jsbin-source-javascript" type="text/javascript">const elevator = {
floor: 5,
up() {
this.floor += 1;
return this;
},
down() {
this.floor -= 1;
return this;
}
};
const newFloor = elevator.up().up().down().up().floor;
console.log(newFloor);
//////////
const elevator2 = {
floor: 5
};
const up =(elevator) => {
return {
floor: elevator.floor + 1
};
};
const down =(elevator) => {
return {
floor: elevator.floor - 1
};
}
const newFloor2 = up(down(up(up(elevator2)))).floor;
console.log(newFloor2);
///////////
const sequence2 = (f1, f2) => (...args) => f2(f1(...args));
const sequence = (f1, ...fRest) => fRest.reduce(sequence2, f1);
const move = sequence(up, up, down, up);
const newElevator = move(elevator);
console.log(newElevator.floor);</script></body>
</html>