Some points regarding readability.
Source code noise reduces overall readability. Noise is anything that is redundant or does not aid in the understanding of the code.
There are many way to introduce noise.
Not addressing the reader
One assumes that the reader of your code is proficient in the language and does not need to be told what various tokens do. You have two comments that assume the coder knows nothing.
// exit case
adds nothing to the code or the readability, thus it is noise and actually detracts from readability.
// recursive case
Really, and I thought it was flying a kite... :P
If you are writing code as a teaching example then you assume the reader has limited knowledge and in that case the obvious is stated in properly structured english (or whatever language)
// exit case
would be // When found exit the function returning the returnResult array.
Note that if you add a comment it should be above the line it refers to with a blank line above it. Or it should be at the end of the line not going past the right margin (80 or I prefer 120 characters)
Thus the example above would be
.
...
return sum === K;
});
// When found exit the function returning the returnResult array.
if (found) {
return returnResult;
}
Or
...
return sum === K;
});
if (found) { // When found exit the function returning the returnResult array.
return returnResult;
}
Misleading the reader
This is the worst type of noise.
Comments are not subject to compilation, verification, or any type of vetting process. The author quickly becomes blind to comments and will overlook them when making changes.
The result is that comments can be in direct opposition of the code they are commenting. This will confuse the reader as to the intent of the code. They are left to guess, is the code in error or the comment.
// main
is a pullover from other languages and is general the entry point of the entire app, there is only one main, and it is only ever called once. It does not apply to JS and should not be used as a comment.
// init
initialize is not accurate, you are defining variable not reenstating them. Some constants can not be initialized as they can not change eg K
. Others can be initialized eg initialize the array arr.length = 0; arr.push(...[1,2,3,4,5]);
Naming noise
We humans read words not by scanning each character in turn, but rather by recognising the shape, and using cues (such as the start and end characters).
Good names are short and to the point. They rely strongly on the context in which they are created to give them meaning. The more frequently a variable is used the shorter it is the better, as you reduce the overall bulk of the code.
returnResult
does the verb return
add to the understanding of the name and what the variable represents. Not at all and thus can be considered naming noise. result
is clear.
We also use abbreviations in code, though you must use the common form, do not make up abbreviations. The common abbreviation for result
is res
getContiguousElementsSum
is incorrect. When you get...
something you know it exists and where it is. The function does not get
a result, it searches for a result and if it exists returns it. Thus replace the get
with find
...Elements...
In JS and most languages the content of an array is referred to as array items, not array elements. In JS this is particularly important as in many contextes elements
refer to DOM objects and thus using the term elements is misleading.
...Sum
No you get items that sum to. getBlahBlahSum
inferes a numeric result which the function does not do.
The function name could be findContiguousItemsSummingTo
It infers how the function works (a search), what the search criteria is (summing to), and what it returns (an array of items).
The name is rather long and there are no convenient abbreviations but the find
in this case can be dropped, items
to arr
, and to
to 2
contiguousArrSumming2
Verbosity
There are many ways to stone a crow, and in most languages that remains true. The best way is the shortest way, less code is more readable by simple virtue of reducing time to read, and making it easier to scan large sections of code.
Readability is in part the ability to write a large code base. A good coder can create apps that have hundreds of thousands of lines of code. Saving 10% is substantial, saving 50% is a order of magnitude easier to comprehend.
You have 6 lines for something that could be one line.
// exit case
if (found) {
return returnResult;
}
// recursive case
return getContiguousElementsSum(arr.slice(1), K);
You have 3 lines that could be one.
if (arr.length === 0 || K < 0) {
return null;
}
They become
if (arr.length === 0 || K < 0) { return }
return found ? res : contiguousArrSumming2((arr.shift(), arr), val);
Note on null
Javascript functions do not return null
Null is a placeholder, it means I have something that I reserve a reference for (Note The idiots people that wrote the DOM API miss used null
). When something is not defined it is undefined
To help reduce code size in JS undefined
is the default return type and need not be defined. return null
is both semantically incorrect and too verbose.
Reducing source code bulk
You can reduce code size using commas to separate lines. We use them in english to keep the size of a text document small and compact, you should do the same in code.
const contiguousArrSumming2 = (arr, val) => {
var sum = 0;
const res = [];
const scan = num => (sum += num, res.push(num), sum === bal);
if (arr.length === 0 ) { return res }
return arr.some(scan) ? res : contiguousArrSumming2(arr.slice(1), val);
};
console.log(contiguousArrSumming2([1, 2, 3, 4, 5], 9));
Personally I would further reduce to
function contiguousArrSumming2(arr, val, res = []) {
var sum = 0;
const scan = num => (sum += num, res.push(num), sum === bal);
return !arr.length || arr.some(scan) ? res : contiguousArrSumming2((arr.shift(), arr), val);
}
A competent coder will have no trouble reading the above code and should instantly spot the very important difference from your original.
Be professional.
Remember those that read your code are professionals. When you present your code and it looks like its a tutorial piece all you do is put distrust in your code as poor/simple language use and pointless comments make you look like a beginner, the result is they will rather rewrite than update or fix, making your efforts pointless.
[2,3,4]
forK=9
. \$\endgroup\$