Answer the question
In order to leave comments, you need to log in
How to improve the performance of js code?
Good day, Khabrovites!
Recently I started to study on codewars and there was a problem with the speed of code execution.
There is a code:
function partsSums(ls) {
ls.reverse();
let a = 0;
arr = [];
let s = ls.length;
for(let i = s; i--;){
for(let j = ls.length; j--;){
a += ls[j];
}
arr.push(a);
ls.pop();
a = 0;
}
arr.push(0);
return ls ? arr : [0];
}
Answer the question
In order to leave comments, you need to log in
there was a problem with the speed of code execution
function partsSums(ls) {
const result = new Array(ls.length + 1);
result[ls.length] = 0;
for (let i = ls.length - 1; i > -1; i--) {
result[i] = result[i + 1] + ls[i];
}
return result;
}
I did it like this:
function partsSums(ls) {
if(ls.length==0) return [0];
result=ls;
result[i=result.length]=0;
i--;
while(i!==-1)
result[i] = result[i+1]+ls[i--];
return result;
}
Test Results:PS link :
partsSums
Basic tests
Random tests
Completed in 2070ms
RAX7 , ... and mine is ~3000ms ¯\_(ツ)_/¯can you squeeze even harder?)
function partsSums(ls) {
ls.unshift(0);
let sum = ls.reduce((p, c) => p + c, 0);
return ls.map(v => sum = sum - v);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question