Last active
February 26, 2021 17:25
-
-
Save gregfenton/b10672dff8181618039189e2f00ac6e7 to your computer and use it in GitHub Desktop.
JAVASCRIPT: EvolveU C5 coding challenge - week #1 - answers
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
// This answer comes in 2 flavours: the "plays nice with others" version and the "hax0rz rUlez!!" version. | |
// | |
//-------------------------------------------------------------------------------------- | |
// PLAYS NICE WITH OTHERS: | |
// | |
const arr2num = (arr) => { | |
return arr | |
.reverse() // work from least-to-most significant digits | |
.reduce( | |
(accumulatedVal, curVal, index) => | |
// multiply by 10 to the power of the significant position (index) | |
(accumulatedVal + Math.abs(curVal) * 10 ** index) * | |
(curVal < 0 ? -1 : 1), | |
null, // return null if given arr is empty | |
); | |
}; | |
const num2arr = (num) => { | |
return num === null | |
? [] // null means arr1 & arr2 were empty arrays | |
: Math.abs(num) | |
.toString() | |
.split('') // array with one element per digit of num | |
.map((i, idx) => | |
// if the first digit and it is negative, make result negative | |
idx === 0 && num < 0 ? new Number(-i) : new Number(i), | |
); | |
}; | |
function addArrays(arr1, arr2) { | |
let a1 = arr2num(arr1); | |
let a2 = arr2num(arr2); | |
let sum; | |
if (a1 && a2) { | |
sum = a1 + a2; | |
} else if (a1) { | |
sum = a1; | |
} else if (a2) { | |
sum = a2; | |
} else { | |
sum = null; | |
} | |
return num2arr(sum); | |
} | |
// | |
// ------------------------------------------------------------------------------------- | |
//-------------------------------------------------------------------------------------- | |
// Hackers Rulez (...NOT!): | |
// | |
const sumOrNull = (v1, v2) => ((v1 || v1 === 0) && (v2 || v2 === 0)) ? v1 + v2 : (v1 || v1 === 0) ? v1 : (v2 || v2 === 0) ? v2 : null; | |
const reNegate = (idx, num) => (idx === 0 && num < 0 ? -1 : 1); | |
const arr2num = (arr) => arr.reverse().reduce((acc, curVal, idx) => (acc + Math.abs(curVal) * 10 ** idx) * (curVal < 0 ? -1 : 1), null) | |
const num2arr = (num) => num === null ? [] : Math.abs(num).toString().split('').map((i, idx) => i * reNegate(idx, num)) | |
function addArrays(arr1, arr2) { | |
return num2arr(sumOrNull(arr2num(arr1), arr2num(arr2))) | |
} | |
// | |
// ------------------------------------------------------------------------------------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment