Last active
September 27, 2017 23:36
-
-
Save kaz-a/d0f2c6fbbe3c4e0748f51e6e75a1b21e to your computer and use it in GitHub Desktop.
JS Bin// source https://jsbin.com/wizehiq
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
// Challenge One | |
const arr = [{ a: 3 }, { a: 55 }, { a: 9 }, { a: 1 }]; | |
const max = (array, arg) => { | |
return array.reduce((a, b) => { | |
if(typeof arg === 'string') { | |
return a[arg] > b[arg] ? a : b; | |
} | |
else if(typeof arg === 'function') { | |
return arg(a) > arg(b) ? a : b; | |
} | |
}) | |
} | |
console.log(max(arr, 'a')); //should output { a: 55 } | |
console.log(max(arr, (x)=> { return x.a % 9 })); //should output { a : 3 } | |
//----------------------------------------------- | |
// Challenge Two | |
const pipeline = (array) => { | |
// const fnA = array[0](1, 2, 3); | |
// const fnB = array[1](fnA); | |
// const fnC = array[2](fnB); | |
// return fnC | |
return function(...args){ | |
const fnA = array[0](...args); | |
const fnB = array[1](fnA); | |
const fnC = array[2](fnB); | |
return fnC | |
} | |
// //BETTER SOLUTION: | |
// return function() { | |
// const fnA = array[0](...arguments); | |
// const nextArray = array.slice(1); | |
// return nextArray.reduce((prev, next) => { | |
// return next(prev) | |
// }, fnA) | |
// } | |
} | |
const a = pipeline([ | |
(a, b, c)=> a + b + c, | |
(x)=> x + 1, | |
(x)=> x - 10 | |
]); | |
const b = pipeline([ | |
(a, b, c, d)=> a * b + c * d, | |
(x)=> x + 1, | |
(x)=> x - 10 | |
]); | |
console.log(a(1, 2, 3));//outputs -3 | |
console.log(b(2, 3, 4, 5));//outputs 17 | |
//----------------------------------------------- | |
// Challenge Three | |
const toMap = (arr, query, err) => { | |
return arr.reduce((returnObj, item) => { | |
let key; | |
typeof query === 'string' ? key = item[query] : key = query(item); | |
if(returnObj[key]) throw new Error("exception") | |
returnObj[key] = item; | |
return returnObj | |
}, {}) | |
} | |
console.log(toMap([ | |
{ x: 3 }, | |
{ x: 6 }, | |
{ x: 8 } | |
], 'x')); | |
/* | |
{ | |
3: { | |
x: 3 | |
}, | |
6: { | |
x: 6 | |
}, | |
8: { | |
x: 8 | |
} | |
} | |
*/ | |
console.log(toMap([ | |
{ x: 3 }, | |
{ x: 3 }, | |
{ x: 8 } | |
], 'x')); | |
// //should throw an exception | |
console.log(toMap([ | |
{ x: 3 }, | |
{ x: 6 }, | |
{ x: 8 } | |
], (item) => item.x * 2)); | |
// /* | |
// { | |
// 12: { | |
// x: 6 | |
// }, | |
// 16: { | |
// x: 8 | |
// }, | |
// 6:{ | |
// x: 3 | |
// } | |
// }*/ | |
console.log(toMap([ | |
{ x: 3 }, | |
{ x: 6 }, | |
{ x: 8 } | |
], (item) => item.x % 2)); | |
// //show throw exception | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment