Functional programming
var add = function(x, y) { return x + y };
const add = (x, y) => x + y;
[1, 4, 9, 16].map((x) => x * 2)
words.filter((word) => word.length > 6)
numbers.reduce((acc, x) => acc + x, 0)
const compose = (a, b) => (c) => a(b(c));
this
arguments
let dog = {
name: 'Sparky'
breed: 'mutt'
}
dog.bark = function() {
console.log(this.name + ": woof!");
}
dog.bark(); // logs "Sparky: woof!"
call()
call(thisArg, arg1, arg2, /* …, */ argN)
function bark() {
console.log(this.name + ": woof!");
}
bark.call(dog);
apply()
apply(thisArg, argsArray);
const numbers = [5, 6, 2, 3, 7];
const max = Math.max.apply(null, numbers);
console.log(max); // 7
bind()
bind(thisArg)
bind(thisArg, arg1, arg2, /* …, */ argN)
const module = {
x: 42,
getX: function () {
return this.x;
},
};
const unboundGetX = module.getX;
console.log(unboundGetX()); // output: undefined
const boundGetX = unboundGetX.bind(module);
console.log(boundGetX()); // output: 42
const add5 = add.bind(null, 5);
add5(10); // 15
function init() {
const name = "Mozilla";
function displayName() {
console.log(name);
}
displayName();
}
init();
function makeFunc() {
const name = "Mozilla";
function displayName() {
console.log(name);
}
return displayName;
}
const myFunc = makeFunc();
myFunc();
const makeCounter = function () {
let privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment() { changeBy(1); },
decrement() { changeBy(-1); },
value() { return privateCounter; },
};
};
const counter1 = makeCounter();
const counter2 = makeCounter();
console.log(counter1.value()); // 0
counter1.increment();
counter1.increment();
console.log(counter1.value()); // 2
console.log(counter2.value()); // 0
fetchData((data) => {
processData(data, (processedData) => {
saveData(processedData, (finalData) => {
console.log("Final Result:", finalData);
});
});
});
fetchData()
.then(processData)
.then(saveData)
.then((finalData) => {
console.log("Final Result:", finalData);
});
>>=
async function main() {
const data = await fetchData();
const processedData = await processData(data);
const finalData = await saveData(processedData);
console.log("Final Result:", finalData);
}
let count = 0;
const rate = 1000;
let lastClick = Date.now() - rate;
document.addEventListener('click', (event) => {
if (Date.now() - lastClick >= rate) {
count += event.clientX;
console.log(count);
lastClick = Date.now();
}
});
import { fromEvent, throttleTime, map, scan } from 'rxjs';
fromEvent(document, 'click')
.pipe(
throttleTime(1000),
map((event) => event.clientX),
scan((count, clientX) => count + clientX, 0)
)
.subscribe((count) => console.log(count));