Skip to content

Commit dd17800

Browse files
Implement function programming on q 149
1 parent fccbb99 commit dd17800

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

code/149-implement-sum.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/*
2+
Given a list of numbers L,
3+
implement a method sum(i, j) which returns the sum from the sublist L[i:j] (including i, excluding j).
4+
5+
For example, given L = [1, 2, 3, 4, 5], sum(1, 3) should return sum([2, 3]), which is 5.
6+
7+
You can assume that you can do some pre-processing.
8+
sum() should be optimized over the pre-processing step.
9+
*/
10+
11+
(() => {
12+
Array.prototype.sum = function (startIndex, endIndex) {
13+
endIndex = endIndex || this.length;
14+
15+
let sum = 0;
16+
for (let i = startIndex; i < endIndex; i++) {
17+
sum += this[i];
18+
}
19+
20+
return sum;
21+
}
22+
23+
const l = [1, 2, 3, 4, 5];
24+
console.log(l.sum(1, 3));
25+
})();

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,8 @@
150150
"145": "nodemon --exec ts-node code/145-swap-every-two-nodes-linked-list.ts",
151151
"146": "nodemon --exec ts-node code/146-prune-a-tree.ts",
152152
"147": "nodemon --exec ts-node code/147-sort-a-list-using-reverse.ts",
153-
"148": "nodemon --exec ts-node code/148-generate-gray-code.ts"
153+
"148": "nodemon --exec ts-node code/148-generate-gray-code.ts",
154+
"149": "nodemon --exec ts-node code/149-implement-sum.js"
154155
},
155156
"keywords": [],
156157
"author": "",

0 commit comments

Comments
 (0)