Skip to content

Instantly share code, notes, and snippets.

@fob2257
Created October 3, 2018 00:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fob2257/ecab9bf666213220fa65faf7401867f1 to your computer and use it in GitHub Desktop.
Save fob2257/ecab9bf666213220fa65faf7401867f1 to your computer and use it in GitHub Desktop.
Functional JS examples
/**
* High order function
*/
{ // using currying
const createScream = fn => message => fn(message.toUpperCase() + '!!!');
const scream = createScream(message => console.log(message));
scream('functions can be returned from other functions');
}
{ // using currying
const greaterThan = base => n => n > base;
const gt10 = greaterThan(10);
console.log(gt10(1));
}
{ // using currying
const simpleOps = fn => (a = 0, b = 0) => {
const sum = a + b;
const sub = a - b;
const div = (b == 0) ? 0 : a / b;
const mul = a * b;
return fn({ sum, sub, div, mul });
}
const myNumbers = simpleOps(v => console.log(v));
myNumbers(5, 3);
}
{
const ages = [12, 12, 54, 32, 50, 65, 5, 33, 23, 65, 7];
const maxAge = ages.reduce((prev, curr) => (curr > prev) ? curr : prev, 0);
console.log(maxAge);
}
/**
* Recursion
*/
{
const countdown = (value, fn) => { fn(value); return (value > 0) ? countdown(value - 1, fn) : 0; };
countdown(10, v => console.log(v));
}
{
const deepPick = (fields, object = {}) => {
const [firstEl, ...remaining] = fields.split('.');
return (remaining.length) ? deepPick(remaining.join('.'), object[firstEl]) : console.log(object[firstEl]);
};
const dan = {
type: "person",
data: {
gender: "male",
info: {
id: 22,
fullname: {
first: "Dan",
last: "Deacon",
},
},
},
};
deepPick('type', dan);
deepPick('data.info.fullname.first', dan);
}
/**
* Composition
*/
{
const oneSecond = () => 1000;
const getCurrentTime = () => new Date();
const clear = () => console.clear();
const log = m => console.log(m);
// mutable objects
const serializeClockTime = date =>
({
hours: date.getHours(),
minutes: date.getMinutes(),
seconds: date.getSeconds(),
});
const civilianHours = clockTime =>
({
...clockTime,
hours: (clockTime.hours > 12) ? clockTime.hours - 12 : clockTime.hours,
});
const appendAMPM = clockTime => ({
...clockTime,
ampm: (clockTime.hours >= 12) ? 'PM' : 'AM',
});
// high order functions
const display = fn => time => fn(time);
const formatClock = format => time =>
format
.replace('hh', time.hours)
.replace('mm', time.minutes)
.replace('ss', time.seconds)
.replace('tt', time.ampm);
const prependZero = key => clockTime =>
({
...clockTime,
[key]: (clockTime[key] < 10) ? `0${clockTime[key]}` : clockTime[key],
});
// composition
const compose = (...fns) => arg =>
fns.reduce(
(composed, f) =>
f(composed),
arg
);
const convertToCivilianTime = clockTime =>
compose(
appendAMPM,
civilianHours
)(clockTime);
const doubleDigits = civilianTime =>
compose(
prependZero('hours'),
prependZero('minutes'),
prependZero('seconds')
)(civilianTime);
const startTicking = () =>
setInterval(
compose(
clear,
getCurrentTime,
serializeClockTime,
convertToCivilianTime,
doubleDigits,
formatClock('hh:mm:ss tt'),
display(log)
), oneSecond()
);
startTicking();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment