Skip to content Skip to sidebar Skip to footer

Prepare Array For Sorting In Closure

According to my research and googling, Javascript seems to lack support for locale aware sorting and string comparisons. There is localeCompare(), but it has been reported of brows

Solution 1:

Is it possible to modify the words-array in between the lines "PREPARATION STARTS" and "PREPARATION ENDS" so that the sort function uses modified words-array?

No, not really. You don't have access to the array itself, your function only builds the compare-function that is later used when .sort is invoked on the array. If you needed to alter the array, you'll need to write a function that gets it as an argument; for example you could add a method on Array.prototype. It would look like

functionmysort(arr) {
    // Preparation// declaration of compare function// OR execution of closure to get the compare function
    arr.sort(comparefn);
    return arr;
}

Is it possible to input arguments to the closure so that code between PREPARATION STARTS and PREPARATION ENDS can use them?

Yes, of course - that is the reason to use closures :-) However, you can't use sortbyalphabet_timo(caseinsensitive) with your current code. The closure you have is immediately invoked (called an IIFE) and returns the compare-function, which you pass into sort as in your demo.

If you want sortbyalphabet_timo to be the closure instead of the result, you have to remove the brackets after it. You also you can use arguments there, which are accessible in the whole closure scope (including the comparefunction):

var sortbyalphabet_timo_closure = function(caseinsensitive) {
    // Preparation, potentially using the arguments// Declaration of compare function, potentially using the argumentsreturn comparefn;
}
// then use
words.sort(sortbyalphabet_timo_closure(true));

Currently, you are doing this:

var sortbyalphabet_timo_closure = function(/*having no arguments*/) {
    // Preparation, potentially using the arguments// Declaration of compare function, potentially using the argumentsreturn comparefn;
}
var sortbyalphabet_timo = sortbyalphabet_timo_closure();
// then use
words.sort(sortbyalphabet_timo);

…which just caches the result of executing the closure, if you'd need to sort multiple times.

Post a Comment for "Prepare Array For Sorting In Closure"