3 ms·
Here's a couple of new things about JS you can learn right now! Currying! Arrow functions! Template strings! function getPrefixer(prefix) { return st
by mevile 10y ago
Here's a couple of new things about JS you can learn right now! Currying! Arrow functions! Template strings!
function getPrefixer(prefix) {
return str => `${prefix}: ${str}`;
}
Now use it!
const infoLogger = getPrefixer('info');
infoLogger('Starting up!'); // returns 'info: Starting up!'
infoLogger('Not being used!'); // 'info: Not being used!'
Oh no, We're throwing the string away, let's use it and have it add a date and use a default argument value!
function getLogger(log, prefix='info') {
return str => log(`${prefix} - ${new Date()}: ${str}`);
}
Now use it!
const infoLogger = getLogger(msg => console.log(msg));
infoLogger('Starting up!'); //Logs 'info - Sat May 28 2016 08:51:12 GMT-0700 (PDT): Starting up!' to console!
const errorLogger = getLogger(msg => { throw msg }, 'error');
errorLogger('Oh no!'); // throws an error with 'error' prefix!
See it in action here with babel:
https://jsfiddle.net/xgwe121v/ https://jsfiddle.net/xgwe121v/
- brown-dragon 10y agoThis is a very cool intro to the new features of JS! Thanks! :-) What part here is Currying?
- mevile 10y agoThe currying part is the variable that you give to the first function. In the first function the prefix variable is stored in the local scope of the big arrow function that is returned. This ability of functions to remember variables from the scope in which they were created is called closures, and storing a variable like this is a closure. Using closures to generate functions with preset variables is currying.