Last active
September 20, 2017 17:59
-
-
Save saurabhpati/54b01f6fcc8e63a86f76af764ddf6f64 to your computer and use it in GitHub Desktop.
creating curry functions to master functional programming. In Progress...
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
var products = [ | |
{ | |
id: 1, | |
name: 'IPhone X', | |
price: 900 | |
}, | |
{ | |
id: 2, | |
name: 'Samsung S8', | |
price: 700 | |
}, | |
{ | |
id: 3, | |
name: 'Moto X', | |
price: 300 | |
}, | |
{ | |
id: 4, | |
name: 'Nokia N6', | |
price: 200 | |
} | |
] | |
// Curry function that return value of a property in an object | |
function prop(property) { | |
return function (arr) { | |
return arr.reduce(function (acc, item) { | |
acc.push(item[property]); | |
return acc; | |
}, []); | |
} | |
} | |
// Curry function that apply map on a given array | |
function map(fn) { | |
return function () { | |
return fn(); | |
} | |
} | |
// Curry function that apply filter on given array | |
function filter(fn) { | |
} | |
// Function that will convert provied string to upper case | |
function toUpper(str) { | |
return function () { | |
return str.toUpperCase(); | |
} | |
} | |
// Curry function that will identify whether the number passed to | |
// second function in curry is less than first number passed in curry | |
function lessThan(num1) { | |
return function (arr) { | |
return arr.filter(function (item) { | |
return item.price < num1; | |
}); | |
}; | |
} | |
// This function will expect multiple arguments as functions. | |
// It will execute them from right-to-left and will pass the | |
// return value of a function to next function in the chain | |
// Hint: Don't convert arguments to array! | |
function compose(fn) { | |
return function (arr) { | |
// Some magic has to be done here. | |
} | |
} | |
var getUpperProductNames = compose(map(toUpper), map(prop('name'))); | |
var productsCheapProducts = compose(filter(compose(lessThan(400), prop('price')))); | |
console.log(getUpperProductNames(products)); // ["IPHONE X", "SAMSUNG S8", "MOTO X", "NOKIA N6"] | |
console.log(productsCheapProducts(products)); | |
// [{ | |
// "id": 3, | |
// "name": "Moto X", | |
// "price": 300 | |
// }, | |
// { | |
// "id": 4, | |
// "name": "Nokia N6", | |
// "price": 200 | |
// }] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment