Become functional – Basic functions

Tue Feb 27 2018

Functional programming becomes the norm, and it has a great hype around it now.

As I mostly used that with redux to make sure my reducers work properly, those function will be helpful for anyone who needs some functional javascript functions.

Ill show some examples below on some simple actions we use like: push to array, remove from array, update item in array and updating object.

The first action will be the mutating one, and the rest would be functional non mutating ones.

Push to array {#pushtoarray}
//******** this mutates original list !!!!!!! *******
const simplePush = (list, item) => {  
    list.push(item);
    return list;
};

const concatPush = (list, item) => {  
    return list.concat([item]);
};

const es6Push = (list, item) => {  
    return [...list, item];
};
Remove from array {#removefromarray}
//******** this mutates original list !!!!!!! *******
const simpleRemove = (list, index) => {  
    list.splice(index, 1);
    return list;
};

const sliceRemove = (list, index) => {  
    return list
        .slice(list, index)
        .concat(list.slice(index+1));
};

const es6Remove = (list, index) => {  
    return [
        ...list.slice(0, index),
        ...list.slice(index + 1)
    ];
};
Update array item {#updatearrayitem}
//******** this mutates original list !!!!!!! *******
const simpleUpdate = (list, index, value) => {  
    list[index] = value;
    return list;
};

const sliceUpdate = (list, index, value) => {  
    return list
        .slice(list, index)
        .concat([value])
        .concat(list.slice(index+1));
};

const es6Update = (list, index, value) => {  
    return [
        ...list.slice(0, index),
        value,
        ...list.slice(index + 1)
    ];
};
Update object value {#updateobjectvalue}
//******** this mutates original list !!!!!!! *******
const simpleUpdate = (obj, key, val) => {  
    obj[key] = val;
    return obj;
};

const assignUpdate = (obj, key, val) => {  
    let updateObj = {};
    updateObj[key] = val;
    return Object.assign({}, obj, updateObj);
};