CodeMonkey CodeMonkey - 3 months ago 8
Javascript Question

Running a simple program in JavaScript

I'm rank new to java script and thus the question. In fact the question has more to do with organization and running of code than the code itself.

So I've a simple problem, I'm trying to set up a boiler plate to write problems and compile using node.

The problem in this case is, given an array of characters and another array of integers, sort the first one int the order specified in the second one. Thus if we have something like,

arr = ['c', 'd', 'e', 'f', 'g'];
indexes = [3, 0, 4, 1, 2];
The answer will be, ['d', 'f', 'g', 'c', 'e']


This is my code,

arr = ['c', 'd', 'e', 'f', 'g'];
indexes = [3, 0, 4, 1, 2];


arranged = function(arr, indexes){
map = {}
for(i=0; i< arr.length; i++){
map.put(indexes[i], arr[i]);
}
Object.keys(map).forEach(function(key){
arr[key] = value;
});
return arr;
};
for(var i in arranged){
console.log(i);
}


This code when I run by calling
node filename.js
yields nothing.

So here are my questions,


  1. How do I organize the code in a way to run, seems like no one is calling the function.

  2. What's are the best practices for organizing and running code, if I go for a coding interview?

  3. Is the program correct?



Any help appreciated. Please don't downvote the question, just because it's not an advanced user question. No where in SO does it mention that it's an exclusive domain of advanced users.

Answer

To answer 3), there are a few mistakes in your code, here's the corrected version:

arranged = function(arr, indexes){
    map = {}
    for(i=0; i< arr.length; i++){
        map[indexes[i]] = arr[i];
    }
    Object.keys(map).forEach(function(key){
        arr[key] = map[key];
    });
    return arr;
};

for(var i of arranged(arr, indexes)){
    console.log(i);
}

This works, but is unnecessary verbose. If you look closer at your arranged function, you'll find out that you don't need the second loop at all!

Comments