0

I'm learning JS and I need help with the following task:

I need to create a function compile_csv_search(text, key_name) that parses text in the CSV format. (not required to handle quoting and escaping in values; assume field values never contain commas or other special characters.)

A function must return a function that looks up a record by a value of the field specified as the second argument to compile_csv_search. Assume that all values in the key field are unique.

Sample usage:

var csv_by_name = compile_csv_search(
    "ip,name,desc\n"+
    "1.94.0.2,server1,Main Server\n"+
    "1.53.8.1,server2,Backup Server\n",
    "name");
console.log(csv_by_name("server2"));
console.log(csv_by_name("server9"));

...will print:

{ip: "10.52.5.1", name: "server2", desc: "Backup Server"}

undefined

** I didn't understand what does it mean "function that return function". How can function return another function?

Thank you!


P.S. attaching my solution for your review

function compile_csv_search(csvServerData){
  var header = csvServerData.split('\n')[0].split(",");
  var spleatedServerData = csvServerData.split('\n');
  return function(serverName)
  {
  for(var i = 1; i < spleatedServerData.length; i++){ 

      var singleServer = spleatedServerData[i].split(',')  
        var result = {};
        var exist = false;  
      for (var j = 0; j < header.length; j++) {
            if(singleServer.indexOf(serverName) == -1) 

                 break;

              exist = true;
            result[header[j]] = singleServer[j];   
        }
        if(exist){
         return(result);
         break; 
        }

    }
 }
}
var csv_by_name = compile_csv_search(
    "ip,name,desc\n"+
    "10.49.1.4,server1,Main Server\n"+
    "10.52.5.1,server2,Backup Server\n");
Aimee Mi
  • 3
  • 3
  • Read: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – user2864740 Aug 28 '14 at 22:25
  • 2
    Here is an example of a function that returns a function: `function foo(name) { return function() { console.log(name); }; } ; foo('bar')();`. Functions are object, so they can be passed to and returned from functions. – Felix Kling Aug 28 '14 at 22:26
  • Make sure to separate the general task from the issue/problem. Parsing the CSV is only a secondary concern (the task) and not related to understanding closures or the problem statement (the issue). – user2864740 Aug 28 '14 at 22:29
  • Take a look at this book, specially this chapter will help understand "how a function can return a function" http://eloquentjavascript.net/03_functions.html – sebagomez Aug 28 '14 at 22:48

2 Answers2

2

Functions in JavaScript are objects; they can be referred to by variables, passed as arguments and returned from functions like any other object.

Here's a function that returns an object:

function returnObject() {
  var result = { a: 1, b: 2, c: 3 };
  return result;
}

And here's a function that returns another function:

function returnFunction() {
  var result = function() { 
    console.log('another function!');
  }

  return result;
}

Notice how they're really similar - object returned by the first function is a plain Object created using object literal syntax ({}), and the object returned by the second happens to be a function.

You could call the inner, returned function like this:

var out = returnFunction();
out();

Or even returnFunction()();

However, you can't just call result() - result is only defined inside of returnFunction. The only way to access it from outside is to retrieve it by calling the outer function.

joews
  • 29,767
  • 10
  • 79
  • 91
0

Something like this would be fine:

function compile_csv_search(text, key_name) {
    var lines = text.split('\n');
    var keys = lines[0].split(',');
    var key_index = keys.indexOf(key_name);
    return function(value) {
        for(var i = 1; i<lines.length; i++) {
            current_line_values = lines[i].split(',');
            if(current_line_values[key_index] === value) {
                var result = {};
                for(var j = 0; j<keys.length; j++) {
                    result[keys[j]] = current_line_values[j];
                }
                return result;
            }
        }
    }
}

Also see this fiddle: http://jsfiddle.net/efha0drq/

You can always treat a function the same as any other js objects. Assign to a variable, pass to a function, store in an array... all are fine.

The magic in this example is that, you can read/write the variables defined in the compile_csv_search() function within the returned function. So it's possible to store something in the local variables of the defining function, and later retrieve from the returned one, even when the defining function has finished execution long time ago. You may have heard of "closure", right?

Tong Shen
  • 1,364
  • 9
  • 17
  • Thank you all, you've helped me a LOT I would like to attached my own solution for your review but i don't know how can it do it here – Aimee Mi Aug 30 '14 at 23:17
  • @AimeeMi You can either edit your question to attach your solution and then @ me, or email me at i[at]tshen.im . – Tong Shen Sep 01 '14 at 04:52