Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

I have been working on a project in JavaScript which requires a data structure (read only), to be shared between two functions.

var mySharedData = ['hours', 'minutes', 'seconds'];

Now I have two functions that need access to this (static) read only data structure.

var sampleFunction1 = function(userSuppliedData) {
    //map over user data applying mySharedData to it
};

var sampleFunction2 = function(userSuppliedData) {
    //reduce user data also accessing mySharedData
};

Since this is JavaScript and both functions are in the same scope I could just "cheat" and leverage the bad scoping of var and access the shared data in both functions but I don't feel like this is the proper way of doing it.

I also considered currying both functions and just passing the shared data as the first argument like so:

var mySharedData = ['hours', 'minutes', 'seconds'];

var sampleFunction1 = _.curry(function(sharedData, userSuppliedData) {
    //map over user data applying sharedData to it
})(mySharedData);

var sampleFunction2 = _.curry(function(sharedData, userSuppliedData) {
    //reduce user data also accessing sharedData
})(mySharedData);

What is the recommended way of sharing data between functions? Should this even be done in functional programming or am I making my functions impure with shared data structures?

share|improve this question
    
The shared data would be common to both closures –  Basile Starynkevitch Aug 22 at 17:00
    
So you suggest doing something like this? function() { //now I'm in a closure var mySharedData = ['hours', 'minutes', 'seconds']; var sampleFunction1 = function(userSuppliedData) { //map over user data applying mySharedData to it }; var sampleFunction2 = function(userSuppliedData) { //reduce user data also accessing mySharedData }; } –  KanskjeBen Aug 22 at 17:42
    
Every user function is implemented as a closure in Javascript –  Basile Starynkevitch Aug 22 at 17:51
2  
Why would you consider using the closure as cheating? –  Idan Arye Aug 22 at 18:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.