简体   繁体   中英

making Ramda.js functions globally accessible (without R. )

I want to use Ramda.js functions without typing R.

I've tried to add all the functions to the global scope but it doesn't work this is my try

const R = require('ramda'); // R is an object containing lots of functions
for(let x in R) {
    global.x = x;
}

also, I want to know how to do it using Ramda library itself.

Make sure you are setting the property called x, rather than the x property: Also, be sure to assign the value of R[x] back, rather than the property name x

global[x] = R[x];

You could also try iterating through getOwnPropertyNames:

for (const prop of Object.getOwnPropertyNames(R)) {
    global[prop] = R[prop]
}

Or, if applicable, just destructure the properties you need into your scope:

const {someProp, someOtherProp} = R;

As per comments, while I disagree that typing additional 2 characters could be termed as a fuss, but it is how you feel.

Like @uber5001 mentioned the de-structure technique, it is one way, but it means you first need to require entire ramda functions into R then retrieve the functions you need.

You can also require only the required functions:

const uniq = require('ramda/src/uniq')
const zip = require('ramda/src/zip')
// and so on

HTH

Setting all the functions of Ramda as globals might be risky. Ramda has a lot of functions, and some of them might override existing globals you have. A better practice (which is still considered a bad practice because you can still shadow-name variables) is the with statement, which destructures all the properties of the object while not overriding your outer scope variables.

with(R) {
  pipe(
    map(x => x ** 2),
    filter(x => x > 24)
  )([3, 4, 5, 6]); // => [25, 36]
}

Note that the with statement is disabled in strict mode.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM