Created
July 5, 2018 07:14
-
-
Save Expl4Life/719dfae0a88927788058577309405d80 to your computer and use it in GitHub Desktop.
HOF - example 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const add = (a, b) => a + b; | |
function isNumber(value) { | |
return typeof value === 'number'; | |
} | |
function withValidator(isValid, operation) { | |
return function (...args) { | |
console.log(...args); | |
console.log(args); | |
if (!args.every(isValid)) { | |
throw new Error("Передан некорректный аргумент"); | |
} | |
return operation.apply(null, args); | |
}; | |
} | |
function withLogger(tag, operation) { | |
return function(...args) { | |
console.log(tag, ...args); | |
return operation.apply(null, args); | |
}; | |
} | |
const numberAdd = withValidator(isNumber, add); | |
const loggedNumberAdd = withLogger('сумма', numberAdd); | |
const loggedAndValidNumberSum = withLogger( | |
'сумма', | |
withValidator(isNumber, add) | |
); | |
console.log(numberAdd(10, 4)); | |
// console.log(loggedNumberAdd(2, 100)); | |
// console.log(loggedAndValidNumberSum(100, 200)); | |
// Функция withValidator несовсемобычная.Она«оборачивает» переданную ей функцию в другую функцию. В качестве аргументов она принимает две функции: | |
// — isValid — функция, которая будет проверять корректность переданных аргументов; | |
// — operation — функция, которую мы будем вызывать если аргументы прошли проверку. | |
// Мыневызываемфункцию operation втеле withValidator.Мы создаём функцию которая будет её вызывать при определенных условиях. Поэтому мы говорим «оборачиваем». |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment