Last active
February 23, 2019 22:17
-
-
Save jaysoo/7b1298bcc98ef9ac71e6dd0383a07dc3 to your computer and use it in GitHub Desktop.
Add a trace function for debugging functional JS code
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
/* | |
* Top level index.js | |
*/ | |
let R = require('ramda') | |
global.trace = msg => R.tap(x => console.log(msg, x)) | |
/* | |
* ... | |
* | |
* Somewhere in the app | |
* | |
*/ | |
let R = require('ramda') | |
let { add, compose, divide, map, multiply, subtract, __ } = R | |
// Function composition using pointfree style | |
let performComplexCalc = compose(subtract(__, 2), divide(__, 4), multiply(10), add(10)) | |
// Maybe there's a bug in our function, but where? | |
map(performComplexCalc, [1, 2, 3, 4, 5]) | |
// To trace through steps, just spinkle `trace` calls in the composition | |
performComplexCalc = compose( | |
trace('after'), | |
subtract(__, 2), | |
divide(__, 4), | |
trace('middle'), | |
multiply(10), | |
add(10), | |
trace('before')) | |
// This way we don't have to resort to changing function to this | |
performComplexCalc = (x) => { | |
console.log('before', x) | |
let result = add(10, x) | |
result = multiply(10, result) | |
console.log('middle', result) | |
result = divide(result, 4) | |
result = subtract(result, 2) | |
console.log('after', result) | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also see @raine's treis.