Skip to content

Instantly share code, notes, and snippets.

@jaysoo
Last active February 23, 2019 22:17
Show Gist options
  • Save jaysoo/7b1298bcc98ef9ac71e6dd0383a07dc3 to your computer and use it in GitHub Desktop.
Save jaysoo/7b1298bcc98ef9ac71e6dd0383a07dc3 to your computer and use it in GitHub Desktop.
Add a trace function for debugging functional JS code
/*
* 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
}
@CrossEye
Copy link

CrossEye commented May 5, 2016

Also see @raine's treis.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment