Skip to content

Instantly share code, notes, and snippets.

@Danziger
Last active July 6, 2017 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Danziger/f4a0f26021900ff833e8bc0ade926347 to your computer and use it in GitHub Desktop.
Save Danziger/f4a0f26021900ff833e8bc0ade926347 to your computer and use it in GitHub Desktop.
Simple JS coding test.
const users = [{
name: 'Charlie',
ranking: 30,
}, {
name: 'Alice',
ranking: 10,
}, {
name: 'Eve',
ranking: 40,
}, {
name: 'Bob',
ranking: 20,
}];
function rank(users) {
// slice(0) will clone the array to leave the original array untouched.
return users.slice(0).sort((a, b) => a.ranking > b.ranking);
}
function calculateAvg(users) {
// Nice, but not performant...
return users.map(user => user.ranking).reduce((total, value) => total + value, 0) / users.length;
}
function calculateAvgFast(users) {
// Much better :D
let i = 0;
let sum = 0;
let total = users.length;
for (;i < total;) {
sum += users[i].ranking;
++i;
}
return sum / total;
}
// rank() test:
const sorted = rank(users).map(user => user.name).join(', ');
const sortedOk = ["Alice", "Bob", "Charlie", "Eve"].join(', ') === sorted;
console.log(`${ sortedOk ? '✔' : '×' } Sorted: ${ sorted }`);
// avg() test:
let avg = calculateAvg(users);
let avgOk = avg === 25;
console.log(`${ avgOk ? '✔' : '×' } Avg: ${ avg }`);
// calculateAvg() performance:
let t0 = performance.now();
let i = 1000000;
while(--i) {
calculateAvg(users);
}
console.log(`Took ${ performance.now() - t0 } ms.`);
// calculateAvgFast() test:
avg = calculateAvgFast(users);
avgOk = avg === 25;
console.log(`${ avgOk ? '✔' : '×' } Avg: ${ avg }`);
// calculateAvgFast() performance:
t0 = performance.now();
i = 1000000;
while(--i) {
calculateAvgFast(users);
}
console.log(`Took ${ performance.now() - t0 } ms.`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment