Skip to content

Instantly share code, notes, and snippets.

@GeorgiyZhuravlev
Last active July 8, 2019 18:14
Show Gist options
  • Save GeorgiyZhuravlev/83ee490e4da5436a2752bdd29212542c to your computer and use it in GitHub Desktop.
Save GeorgiyZhuravlev/83ee490e4da5436a2752bdd29212542c to your computer and use it in GitHub Desktop.
function getCountdown() {
// diff in seconds, comes through function's params
const diff = 60*60*24*4 + 60*60*22 + 60*35 + 5;
const MINUTE = 60;
const HOUR = MINUTE * 60;
const DAY = HOUR * 24;
const days = Math.floor(diff / DAY);
const hDiff = diff % DAY;
const hours = Math.floor(hDiff / HOUR);
const mDiff = hDiff % HOUR;
const minutes = Math.floor(mDiff / MINUTE);
const seconds = mDiff % MINUTE;
return [days, hours, minutes, seconds]
.map(v => (''+v)[1] ? ''+v : '0'+v)
}
// output: ["04", "22", "35", "05"]
const sortFn = (propPath, isReverse = false) => (objA, objB) => {
// lodash dependency
const a = _.get(objA, propPath);
const b = _.get(objB, propPath);
const isNumbers = (typeof a === 'number') && (typeof b === 'number');
const isStrings = (typeof a === 'string') && (typeof b === 'string');
const isDates = (a instanceof Date) && (b instanceof Date);
if (isNumbers || isDates) {
return isReverse ? b - a : a - b
} else if (isStrings) {
return isReverse ? b.localeCompare(a) : a.localeCompare(b)
} else {
return 0; // don't know how to compare so equals
}
}
// array to sort
const arr = [
{num: 1, str: 'ddd', date: new Date('2008-12-17T03:24:00'), nested: {num: 4}},
{num: 5, str: 'zzz', date: new Date('2000-12-17T03:24:00'), nested: {num: 2}},
{num: 2, str: 'aaa', date: new Date('2018-12-17T03:24:00'), nested: {num: 9}},
]
console.log({
byNumber: [...arr].sort(sortFn('num')),
byNumberRev: [...arr].sort(sortFn('num', true)),
byString: [...arr].sort(sortFn('str')),
byStringRev: [...arr].sort(sortFn('str', true)),
byDate: [...arr].sort(sortFn('date')),
byDateRev: [...arr].sort(sortFn('date', true)),
byNested: [...arr].sort(sortFn('nested.num')),
byNestedRev: [...arr].sort(sortFn('nested.num', true))
});
// https://stripe.com/docs/billing/subscriptions/tiers
/*
plans = [
{upTo: 10, price: 5},
{upTo: 25, price: 4},
{upTo: 50, price: 3},
{upTo: null, price: 2}
]
for 15 users = 10 * 5 + 5 * 4
for 30 users = 10 * 5 + 15 * 4 + 5 * 3
for 57 users = 10 * 5 + 15 * 4 + 25 * 3 + 7 * 2
*/
function getTotal(plans, num) {
return plans.reduce((acc, cur) => {
var quota = cur.upTo ? cur.upTo - acc.prev : Number.MAX_SAFE_INTEGER;
var n = acc.rest - quota;
acc.sum += cur.price * (n > 0 ? quota : acc.rest);
acc.rest = n > 0 ? n : 0;
acc.prev = cur.upTo;
return acc;
}, {sum: 0, prev: 0, rest: num}).sum
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment