Skip to content

Instantly share code, notes, and snippets.

View gladchinda's full-sized avatar

Glad Chinda gladchinda

View GitHub Profile
function sum() {
// Convert arguments to array
var args = Array.prototype.slice.call(arguments);
// Compute sum using array reduce()
return args.reduce(function(a, b) { return a + Number(b) }, 0);
}
function sum(...args) {
// Compute sum using array reduce()
return args.reduce((a, b) => a + Number(b), 0);
}
const scores = [42, 68, 49, 83, 72, 65, 77, 74, 86, 51, 69, 47, 53, 58, 51];
const totalScore = sum.apply(null, scores);
const averageScore = totalScore / scores.length;
console.log(totalScore); // 945
console.log(averageScore); // 63
// USING REGULAR FUNCTION
const getTimestamp = function() {
return +new Date;
}
// USING ARROW FUNCTION
const getTimestamp = () => {
return +new Date;
}
// Returned object literal wrapped in parentheses
const getProfile = () => ({
name: 'Glad Chinda',
gender: 'Male',
birthday: 'August 15'
});
// Pair of parentheses is omitted
const computeSquare = num => num * num;
// Pair of parentheses cannot be omitted
const addNumbers = (numA, numB) => numA + numB;
// The traditional function body wrapped in curly braces
// is used here to aid readability.
// Pair of parentheses cannot be omitted
const factorial = (n = 1) => {
return (n <= 1) ? 1 : n * factorial(n - 1);
}
// Pair of parentheses cannot be omitted
const range = (...numbers) => Math.max(...numbers) - Math.min(...numbers);
const snakeCase = value => {
const regex = /[A-Z][^A-Z]+/g;
const withoutSpaces = value.trim().replace(/\s+/g, '_');
const caps = withoutSpaces.match(regex);
const splits = withoutSpaces.split(regex);
let finalString = splits.shift();
for (let i = 0; i < splits.length; i++) {