Crossing to the other side: Functional Javascripting

Alex Badea

First Impressions

Is it better?

Is it difficult?

Is it completely different?

The tools

  • Pure functions
  • Function composition
  • Immutability

Pure functions

Impure Pure functions

let state;

const impureFunction = (...params) => {

    // do stuff with params

    state = 'hamster';

}

let state = {};

const alsoImpureFunction = (state) => {

    // do stuff with params

    state.myPet = 'hamster';

}

const alsoAlsoImpureFunction = () => {

    const someData = document.querySelectAll('intuitiveClassName')

        .map(domElem => domElem.dataset.intuitivePropName);

 

    fetch("/path", {

        method: "POST",

        body: JSON.stringify(someData),

    }).then(/* update stuff here */);

};

Pure functions

Text

let state;

const pureFunction = (...param) => {

    // do stuff with params

    return 'hamster';

}

state = pureFunction();

let state;

const impureFunction = (...params) => {

    // do stuff with params

    state = 'hamster';

}

Text

let state = {};

const alsoPureFunction = (state = {}) => {

    const newState = Object.assign({}, state);

    // do stuff with params

    newState.myPet = 'hamster';

    return newState;

}

state = alsoPureFunction(state);

let state = {};

const alsoImpureFunction = (state) => {

    // do stuff with params

    state.myPet = 'hamster';

}

Text

const getDataSet = (className) => document.querySelectAll(className)

    .map(domElem => domElem.dataset.prop);

const fetchFromServer = (dataArray) => {

    fetch("/path", {

        method: "POST",

        body: JSON.stringify(dataArray),

    }).then(resp => resp.json());

};

const alsoAlsoPureFunction = async (className) => {

    const serverData = await fetchFromServer(getDataSet(className));

    // do stuff with serverData

    return parsedServerData;

};

const alsoAlsoImpureFunction = () => {

    const someData = document.querySelectAll('intuitiveClassName')

        .map(domElem => domElem.dataset.intuitivePropName);

 

    fetch("/path", {

        method: "POST",

        body: JSON.stringify(someData),

    }).then(/* update stuff here */);

};

Function composition

const parseUserNames = userArray => userArray

        .map(user => `${user.firstName} ${user.lastName}`);

 

const validateUserNames = userNameArray => userNameArray

        .every(name => name.length < 50 && name.length > 5);

 

validateUserNames(parseUserNames(userList));

Partial application

const greetPerson = (greeting = 'Hello', message = 'Have an awesome day!', name) => {

    return `${greeting} ${name}! ${message}`;

};

const britishGreet = (greeter, name) => {

    return greeter('Rainnin\' cats and dogs, innit,', 'Can I shag a fag off ya?', name);

};

const britishGreet2 = greetPerson.bind(null, 'Rainnin\' cats and dogs, innit,', 'Can I shag a fag off ya?');

Currying

const greet = (greeting = 'Hello') => {

    return (name = 'Stranger') => {

        return (message = 'Have a nice day!') => `${greeting} ${name}! ${message}`;

    }

}

greet('Hey')('Alex')('You are an awesome programmer!!');

 

const sayHey = greet('Hey');

sayHey('Alex')('Just kidding');

 

const messageAlex = sayHey('Alex');

messageAlex('No seriously...');

Immutabilty

const user = {

    settings: {

        landingPage: 'home',

        theme: 'dark',

    }

};

Object.freeze(user);

const userClone = Object.assign({}, user);

 

user.settings.landingPage = 'not home';

userClone.settings.theme = 'light';

Immutable JS

Mori

Seamless immutable

Freezer

Mutatis

React's immutability helpers

Crossing to the other side: Functional Javascripting

By alexb_90

Crossing to the other side: Functional Javascripting

  • 462