JavaScript / ES6

Get max value from an array of objects

ES6 spread operator with Math.max makes it clean and simple.

Math.max(...arrayOfObjects.map(x => x.value), 0);

 

SinonJS mock current date & time in unit tests

Use sinonjs to mock / stub the date returned from moment() and new Date() in your unit tests.

// set date to 01 Jan 2018 for unit tests
sinon.useFakeTimers(new Date('2018-01-01T00:00'));

 

ES6 destructuring an object with string keys

For properties that can't be accessed with dot notation because they contain things like hyphens or spaces.

// object with hyphenated props
let person = {
  "first-name": "Jason",
  "last-name": "Watmore"
};

// ES6 destructure to assign props to variables using key: variable notation
let { "first-name": firstName, "last-name": lastName } = person;

 

Get date diff in days between two dates

Get the difference between two dates using the built in JavaScript Date and Math objects.

function daysBetween(startDate, endDate) {
    var millisecondsPerDay = 1000 * 60 * 60 * 24;
    var startDateUTC = Date.UTC(startDate.getFullYear(), startDate.getMonth(), startDate.getDate());
    var endDateUTC = Date.UTC(endDate.getFullYear(), endDate.getMonth(), endDate.getDate());

    return Math.floor((endDateUTC - startDateUTC) / millisecondsPerDay);
}

Supported by