Skip to content

Commit

Permalink
Prefer ES2016 and functional loops over ES5 and imperative counterparts
Browse files Browse the repository at this point in the history
  • Loading branch information
Aaron Sky committed May 21, 2017
1 parent 3b1a1c1 commit e5bde49
Show file tree
Hide file tree
Showing 11 changed files with 62 additions and 61 deletions.
4 changes: 2 additions & 2 deletions app/config/rc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ function loadOpts(optsPath?: string): IbizanConfig {
if (!fs.existsSync(optsPath)) {
return makeEmptyConfig();
}
let contents;
let contents: string[];
try {
contents = fs.readFileSync(optsPath, 'utf8')
.replace('/\\\s/g', '%20')
Expand All @@ -88,7 +88,7 @@ function loadOpts(optsPath?: string): IbizanConfig {
let key: string = null;
let buffer: string[] = [];
contents.forEach((element) => {
if (element.indexOf('--') && keys.indexOf(element.replace('--', '')) !== -1) {
if (element.includes('--') && keys.includes(element.replace('--', ''))) {
if (key && buffer.length > 0) {
config[key] = buffer;
buffer = [];
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/hound.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ function hound(slackuser: { id: string; name: string }, channel: { private?: boo
if (!channel.private) {
channel.private = !!channel.is_im || !!channel.is_group;
}
if (channel.private || organization.exemptChannels.indexOf(channel.name) !== -1) {
if (channel.private || organization.exemptChannels.includes(channel.name)) {
console.debug(`#${channel.name} is not an appropriate hounding channel`);
return;
}
Expand Down
30 changes: 15 additions & 15 deletions app/controllers/time.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,24 +147,15 @@ async function sendPunch(punch: Punch, user: User, message: Message, organizatio
}
}

function onModeHandler(bot: botkit.Bot, message: Message) {
function onPunchHandler(bot: botkit.Bot, message: Message) {
const organization: Organization = message.organization;
if (!organization) {
console.error('No Organization was found for the team: ' + bot);
return;
}
parse(bot, message, message.match[1] as Mode, organization);
}
function onBlockTimeHandler(bot: botkit.Bot, message: Message) {
function onGivenModeHandler(bot: botkit.Bot, message: Message) {
const organization: Organization = message.organization;
if (!organization) {
console.error('No Organization was found for the team: ' + bot);
return;
}
parse(bot, message, message.match[1] as Mode, organization);
}
}

async function onAppendHandler(bot: botkit.Bot, message: Message) {
const organization: Organization = message.organization;
if (!organization) {
Expand Down Expand Up @@ -241,6 +232,7 @@ async function onAppendHandler(bot: botkit.Bot, message: Message) {
user.directMessage(message.copy.time.addFail);
}
}

async function onUndoHandler(bot: botkit.Bot, message: Message) {
const organization: Organization = message.organization;
if (!organization) {
Expand Down Expand Up @@ -268,6 +260,7 @@ async function onUndoHandler(bot: botkit.Bot, message: Message) {
user.directMessage(message.copy.time.undoFail);
}
}

function onUpcomingEventsHandler(bot: botkit.Bot, message: Message) {
const organization: Organization = message.organization;
if (!organization) {
Expand All @@ -288,6 +281,7 @@ function onUpcomingEventsHandler(bot: botkit.Bot, message: Message) {
bot.say(msg);
Slack.addReaction('dog2', message);
}

function onHoursHelpHandler(bot: botkit.Bot, message: Message) {
const msg = {
text: message.copy.time.hoursHelp,
Expand All @@ -296,6 +290,7 @@ function onHoursHelpHandler(bot: botkit.Bot, message: Message) {
bot.say(msg);
Slack.addReaction('dog2', message);
}

function onHoursForDateHandler(bot: botkit.Bot, message: Message) {
const organization: Organization = message.organization;
if (!organization) {
Expand Down Expand Up @@ -354,6 +349,7 @@ function onHoursForDateHandler(bot: botkit.Bot, message: Message) {
Slack.addReaction('dog2', message);
user.directMessage(msg, attachments);
}

function onHoursForPeriodHandler(bot: botkit.Bot, message: Message) {
const organization: Organization = message.organization;
if (!organization) {
Expand Down Expand Up @@ -464,6 +460,7 @@ function onHoursForPeriodHandler(bot: botkit.Bot, message: Message) {
Slack.addReaction('dog2', message);
user.directMessage(msg, attachments);
}

function onUserStatusHandler(bot: botkit.Bot, message: Message) {
const organization: Organization = message.organization;
if (!organization) {
Expand All @@ -474,6 +471,7 @@ function onUserStatusHandler(bot: botkit.Bot, message: Message) {
user.directMessage('Your status:', [user.slackAttachment()]);
Slack.addReaction('dog2', message);
}

function onUserTimeHandler(bot: botkit.Bot, message: Message) {
const organization: Organization = message.organization;
if (!organization) {
Expand All @@ -490,6 +488,7 @@ function onUserTimeHandler(bot: botkit.Bot, message: Message) {
user.directMessage(msg);
Slack.addReaction('dog2', message);
}

function onUserTimezoneHandler(bot: botkit.Bot, message: Message) {
const organization: Organization = message.organization;
if (!organization) {
Expand All @@ -501,6 +500,7 @@ function onUserTimezoneHandler(bot: botkit.Bot, message: Message) {
user.directMessage(`Your timezone is set to *${user.timetable.timezone.name}* (${userTime.format('z, Z')}).`);
Slack.addReaction('dog2', message);
}

function onSetUserTimezoneHandler(bot: botkit.Bot, message: Message) {
const organization: Organization = message.organization;
if (!organization) {
Expand All @@ -516,7 +516,7 @@ function onSetUserTimezoneHandler(bot: botkit.Bot, message: Message) {
isTzSet = true;
} else {
// Try adding 'America/' if a region is not specified
if (input.indexOf('/') === -1) {
if (!input.includes('/')) {
input = 'America/' + input;
}
if (tz = user.setTimezone(input)) {
Expand All @@ -537,6 +537,7 @@ function onSetUserTimezoneHandler(bot: botkit.Bot, message: Message) {
Slack.addReaction('x', message);
}
}

function onSetUserActiveTimesHandler(bot: botkit.Bot, message: Message) {
const organization: Organization = message.organization;
if (!organization) {
Expand Down Expand Up @@ -590,23 +591,22 @@ function onSetUserActiveTimesHandler(bot: botkit.Bot, message: Message) {
}
}


export default function (controller: botkit.Controller) {
// Punch for a given mode
// respond
// time.punchByMode, userRequired: true
controller.hears(REGEX_STR.modes,
EVENTS.respond,
buildOptions({ id: 'time.punchByMode', userRequired: true }, controller),
onModeHandler);
onPunchHandler);

// Punch for a block of time
// respond
// 'time.punchByTime', userRequired: true
controller.hears(REGEX_STR.rel_time,
EVENTS.respond,
buildOptions({ id: 'time.punchByTime', userRequired: true }, controller),
onBlockTimeHandler);
onPunchHandler);

// Switch projects during an 'in' punch
// append to lastPunch
Expand Down
2 changes: 1 addition & 1 deletion app/i18n/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace Copy {
export let defaultLocale = '';

export function setDefaultLocale(locale: string) {
if (acceptableLanguages.indexOf(locale) !== -1) {
if (acceptableLanguages.includes(locale)) {
defaultLocale = locale;
console.log(`Set the default locale to ${locale}`);
}
Expand Down
2 changes: 1 addition & 1 deletion app/middleware/receive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export function applyReceiveMiddleware(controller: botkit.Controller) {
}

function onReceiveSwallowBlacklistedMessageTypes(bot: botkit.Bot, message: Message, next: () => void) {
if (BLACKLISTED_SLACK_MESSAGE_TYPES.indexOf(message.type) === -1) {
if (!BLACKLISTED_SLACK_MESSAGE_TYPES.includes(message.type)) {
next();
}
}
Expand Down
20 changes: 9 additions & 11 deletions app/models/organization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,9 +235,9 @@ export class Organization {
if (upcomingEvents.length > 0) {
const now = moment().subtract(1, 'days');
response += "\nUPCOMING EVENTS:\n";
for (let upcomingEvent of upcomingEvents) {
const days = upcomingEvent.date.diff(now, 'days');
const weeks = upcomingEvent.date.diff(now, 'weeks');
upcomingEvents.forEach(event => {
const days = event.date.diff(now, 'days');
const weeks = event.date.diff(now, 'weeks');
let daysArticle = "day";
if (days > 1) {
daysArticle += "s"
Expand All @@ -249,26 +249,24 @@ export class Organization {
if (weeks > 0) {
const daysRemainder = days % 7 || 0;
daysArticle = daysRemainder > 1 ? 'days' : 'day';
response += `${upcomingEvent.name} in ${weeks} ${weeks > 1 ? 'weeks' : 'week'}${daysRemainder > 0 ? ', ' + daysRemainder + ' ' + daysArticle : ''}\n`
response += `${event.name} in ${weeks} ${weeks > 1 ? 'weeks' : 'week'}${daysRemainder > 0 ? ', ' + daysRemainder + ' ' + daysArticle : ''}\n`
} else {
response += `*${upcomingEvent.name}* ${days > 1 ? 'in *' + days + ' days*' : '*tomorrow*'}\n`
response += `*${event.name}* ${days > 1 ? 'in *' + days + ' days*' : '*tomorrow*'}\n`
}
}
});
}
return response;
}

resetHounding() {
let i = 0;
for (let user of this.users) {
return this.users.reduce((acc, user) => {
if (user.settings && user.settings.shouldResetHound) {
user.settings.fromSettings({
shouldHound: true
});
}
i += 1;
}
return i;
return acc + 1;
}, 0);
}

setHoundFrequency(frequency: number) {
Expand Down
6 changes: 2 additions & 4 deletions app/models/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,8 @@ export class Project {
}
}
hexColor() {
let hash = 0;
for (let i = 0, len = this.name.length; i < len; i++) {
hash = this.name.charCodeAt(i) + ((hash << 3) - hash);
}
const hash = this.name.split('')
.reduce((acc, char) => char.charCodeAt(0) + ((acc << 3) - acc), 0);
const color = Math.abs(hash).toString(16).substring(0, 6);
const hexColor = "#" + '000000'.substring(0, 6 - color.length) + color;
return hexColor;
Expand Down
17 changes: 6 additions & 11 deletions app/models/punch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ function parseMode(command: string): [string, string] {
mode = mode.trim();
commandWithoutMode = commandWithoutMode || '';
commandWithoutMode = commandWithoutMode.trim();
if (MODES.indexOf(mode) !== -1) {
if (MODES.includes(mode)) {
return [mode, commandWithoutMode];
}
return ['none', commandWithoutMode];
Expand Down Expand Up @@ -132,7 +132,7 @@ function parseDate(command: string): [moment.Moment[], string] {
command = command.replace(pattern, '');
} else if (match = command.match(REGEX.date)) {
// Placeholder for date blocks
if (match[0].indexOf('-') !== -1) {
if (match[0].includes('-')) {
const dateStrings = match[0].split('-')
let month = ''
for (let str of dateStrings) {
Expand All @@ -151,7 +151,7 @@ function parseDate(command: string): [moment.Moment[], string] {
const pattern = new RegExp(match[0] + ' ?', 'i');
command = command.replace(pattern, '');
} else if (match = command.match(REGEX.numdate)) {
if (match[0].indexOf('-') !== -1) {
if (match[0].includes('-')) {
const dateStrings = match[0].split('-')
let month = ''
for (let str of dateStrings) {
Expand Down Expand Up @@ -339,7 +339,7 @@ export class Punch {

const datetimes: PunchTime = [];
const tz = user.timetable.timezone.name;
for (var i = 0; i < 2; i++) {
for (let i = 0; i < 2; i++) {
const rawPunchTime = row[MODES[i]];
if (row[MODES[i]]) {
let newDate = moment.tz(rawPunchTime, 'MM/DD/YYYY hh:mm:ss a', TIMEZONE);
Expand Down Expand Up @@ -441,7 +441,7 @@ export class Punch {

if (!project) {
continue;
} else if (this.projects.indexOf(project) === -1) {
} else if (!this.projects.includes(project)) {
this.projects.push(project);
}
}
Expand Down Expand Up @@ -747,14 +747,9 @@ export class Punch {
}
const words = this.notes.split(' ');
warnings = {
projects: [],
projects: words.filter(word => word.charAt(0) === '#'),
other: []
};
for (let word of words) {
if (word.charAt(0) === '#') {
warnings.projects.push(word);
}
}
} else {
if (projectsQualifier) {
notesQualifier = ')';
Expand Down
14 changes: 7 additions & 7 deletions app/models/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ export class User {
if (this.punches && this.punches.length > 0) {
for (let len = this.punches.length, i = len - 1; i >= 0; --i) {
const last = this.punches[i];
if (modes.indexOf(last.mode) !== -1) {
if (modes.includes(last.mode)) {
return last;
}
}
Expand Down Expand Up @@ -315,8 +315,9 @@ export class User {
lastPunch.times.pop();
lastPunch.elapsed = null;

if (lastPunch.notes.lastIndexOf('\n') > 0) {
lastPunch.notes = lastPunch.notes.substring(0, lastPunch.notes.lastIndexOf('\n'));
const lineBreakIndex = lastPunch.notes.lastIndexOf('\n');
if (lineBreakIndex > 0) {
lastPunch.notes = lastPunch.notes.substring(0, lineBreakIndex);
}

lastPunch.mode = 'in';
Expand Down Expand Up @@ -349,7 +350,7 @@ export class User {
unpaidTime = 0,
vacationTime = 0,
sickTime = 0;
const projectsForPeriod = []
const projectsForPeriod = [];
for (let punch of this.punches) {
if (punch.date.isBefore(start) || punch.date.isAfter(end)) {
continue;
Expand Down Expand Up @@ -460,9 +461,8 @@ export class User {
this.updateRow();
}
hexColor() {
const hash = this.slackName.split('').reduce((acc, char, index) => {
return char.charCodeAt(0) + ((acc << 3) - acc);
}, 0);
const hash = this.slackName.split('')
.reduce((acc, char) => char.charCodeAt(0) + ((acc << 3) - acc), 0);
const color = Math.abs(hash).toString(16).substring(0, 6);
const hexColor = "#" + '000000'.substring(0, 6 - color.length) + color;
return hexColor;
Expand Down
24 changes: 17 additions & 7 deletions app/shared/constants.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@

export const REGEX = {
interface RegexConstants {
ibizan: RegExp;
modes: RegExp;
days: RegExp;
rel_time: RegExp;
time: RegExp;
months: RegExp;
date: RegExp;
numdate: RegExp;
}
export const REGEX: RegexConstants = {
ibizan: /^(?:@)?ibizan(?::)? ?/i,
modes: /\b(in|out|vacation|sick|unpaid)\b/i,
days: /monday|tuesday|wednesday|thursday|friday|saturday|sunday/i,
Expand All @@ -10,12 +20,12 @@ export const REGEX = {
numdate: /((?:\b(0?2)\/(0?[1-9]|[1-2][0-9])\b)|(?:\b(0?[469]|11)\/(0?[1-9]|[1-2][1-9]|30)\b)|(?:\b(0?[13578]|(10|12))\/(0?[1-9]|[1-2][1-9]|3[01])\b))(?: ?- ?((?:\b(0?2)\/(0?[1-9]|[1-2][0-9])\b)|(?:\b(0?[469]|11)\/(0?[1-9]|[1-2][1-9]|30)\b)|(?:\b(0?[13578]|(10|12))\/(0?[1-9]|[1-2][1-9]|3[01])\b)))?(?:\/((19[6-9][0-9])|(2[0-9]{3})))?/i,
};

let regexStringVariants: any = {};
for (let key in REGEX) {
let regexString = REGEX[key].toString();
regexStringVariants[key] = regexString.substring(1, regexString.indexOf('/i'));
}
export const REGEX_STR = regexStringVariants;
export const REGEX_STR = Object.keys(REGEX)
.reduce((acc, key) =>
REGEX[key].toString().substring(1, REGEX[key].toString().indexOf('/i')),
{} as {
[key in keyof RegexConstants]: string;
});

export const MODES = ['in', 'out', 'vacation', 'sick', 'unpaid'];

Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"compilerOptions": {
"target": "es6",
"target": "es2016",
"module": "commonjs",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
Expand Down

0 comments on commit e5bde49

Please sign in to comment.