Skip to content

Commit

Permalink
Finishes cleaning '/src/utils'. codeforboston#1018. Also codeforbosto…
Browse files Browse the repository at this point in the history
…n#708.

Maybe fixes both of those. We shall see.
  • Loading branch information
knod committed Dec 2, 2018
1 parent 91a1908 commit d2ae9d3
Show file tree
Hide file tree
Showing 8 changed files with 87 additions and 76 deletions.
2 changes: 1 addition & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import ReactDOM from 'react-dom';
import './index.css';
import './styles/dev.css';
import App from './App';
import registerServiceWorker from './utils/registerServiceWorker';
import { registerServiceWorker } from './utils/registerServiceWorker';
import 'semantic-ui-css/semantic.min.css';

ReactDOM.render(<App />, document.getElementById('root'));
Expand Down
41 changes: 21 additions & 20 deletions src/utils/math.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
/** For different kinds of math operations we need, some unconventional */
/** For different kinds of math operations we need, some unconventional
* @module
*/

const sum = function (vals) {
let total = 0;
Expand All @@ -14,39 +16,38 @@ const roundMoney = function (val) {
// storage objects, keep things exact. Also, this doesn't restrict
// to two decimal places. Do that in the input's attributes.
return (Math.round(val * 100) / 100); // val = '' returns 0
}; // End roundMoney()
};


/** This is how we've seen it done in MA tables
*
* @see Math was observed at {link http://www.mass.gov/eohhs/docs/masshealth/deskguides/fpl-deskguide.pdf}
* @see More notes on data at {link https://docs.google.com/document/d/1DRNm1TLP31s_yDdsH8IDoRV7_KjjJ46NyAaZOgLoQmY/edit#}
* @todo Implement US State specific rounding? Benefit program-specific?
*/
const moneyToWholeNum = function (val) {
return Math.ceil(val);
};


/**
* Turns a value into a float, limits it in between min and max, and
* makes sure to return a number (not NaN).
*
* @todo Testing required
*/
* Turns a value into a float, limits it in between min and max, and
* makes sure to return a number (not NaN).
*/
const limit = function (initialVal, minMax) {

/** @todo Add trailing 0's somewhere */
// @todo Add trailing 0's somewhere
let min = minMax.min,
max = minMax.max;

let raw = parseFloat(initialVal),
value = raw;

if (typeof min === 'number' && !isNaN(min)) {
if (typeof min === `number` && !isNaN(min)) {
value = Math.max(min, raw);
}

if (typeof max === 'number' && !isNaN(max)) {
if (typeof max === `number` && !isNaN(max)) {
value = Math.min(max, raw);
}

Expand All @@ -55,37 +56,37 @@ const limit = function (initialVal, minMax) {
}

return value;
}; // End limit()
};


let toMonthlyAmount = {};

/** @see {@link https://docs.google.com/document/d/13kb1hsxMi6pN9oAUGsTatDz4OSX5IeDLF9B-ddPjMCk/edit#heading=h.hxz256tmbsz9} */
toMonthlyAmount.weekly = function (evnt, weeklyVal) {

/** @see {@link https://docs.google.com/document/d/13kb1hsxMi6pN9oAUGsTatDz4OSX5IeDLF9B-ddPjMCk/edit#heading=h.hxz256tmbsz9} */
let monthlyRaw = weeklyVal * (4 + 1 / 3),
monthly = toMonthlyAmount[ 'monthly' ](evnt, monthlyRaw);
let monthlyRaw = weeklyVal * (4 + 1 / 3),
monthly = toMonthlyAmount[ `monthly` ](evnt, monthlyRaw);
return monthly;

}; // End toMonthlyAmount.weekly()
};


toMonthlyAmount.monthly = function (evnt, monthlyVal) {
// Monthly is used for a lot of things and is the one we want to store
let monthlyInBounds = limit(monthlyVal, { min: 0 });
return monthlyInBounds;

}; // End toMonthlyAmount.monthly()
};


/** @see {@link https://docs.google.com/document/d/13kb1hsxMi6pN9oAUGsTatDz4OSX5IeDLF9B-ddPjMCk/edit#heading=h.hxz256tmbsz9} */
toMonthlyAmount.yearly = function (evnt, yearlyVal) {

/** @see {@link https://docs.google.com/document/d/13kb1hsxMi6pN9oAUGsTatDz4OSX5IeDLF9B-ddPjMCk/edit#heading=h.hxz256tmbsz9} */
let monthlyRaw = (yearlyVal / 12),
monthly = toMonthlyAmount[ 'monthly' ](evnt, monthlyRaw);
let monthlyRaw = (yearlyVal / 12),
monthly = toMonthlyAmount[ `monthly` ](evnt, monthlyRaw);
return monthly;

}; // End toMonthlyAmount.yearly()
};


export {
Expand Down
12 changes: 6 additions & 6 deletions src/utils/objectKeyPaths.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@
* // [ 'e', 'f', 'g', 'h' ]
* // ]
*/
const getKeyPathsArray = (obj, stripVersions, base = []) => {
const getKeyPathsArray = function (obj, stripVersions, base = []) {
// Array to contain our keys paths (if any)
let pathsArr = [],
versionRegex = /_v\d+$/;
Expand All @@ -80,7 +80,7 @@ const getKeyPathsArray = (obj, stripVersions, base = []) => {
return pathsArr;

// Return an array of paths to each prop using the base path and the key in each loop iteration
} else if (typeof obj === 'object') {
} else if (typeof obj === `object`) {
const keys = Object.keys(obj).sort();

// Handle having an empty object
Expand Down Expand Up @@ -109,13 +109,13 @@ const getKeyPathsArray = (obj, stripVersions, base = []) => {
pathsArr = pathsArr.concat(childPaths);
}
return pathsArr;
}
} // ends if there are or aren't any keys

// Otherwise, we've got some sort of primative such as a str, num, etc, so don't do anything
} else {
return pathsArr;
}
};
} // ends if is or isn't an array
}; // Ends getKeyPathsArray()


/**
Expand Down Expand Up @@ -146,7 +146,7 @@ const getKeyPathsArray = (obj, stripVersions, base = []) => {
* // 'e.f.g.h'
* // ]
*/
const getKeyPathStrings = (keyPathsArr) => {
const getKeyPathStrings = function (keyPathsArr) {
return keyPathsArr.map((keyPath) => {
return keyPath.join('.');
});
Expand Down
3 changes: 2 additions & 1 deletion src/utils/prettifiers.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
/**
* Functions for making client values into values
* that users will see.
* @module
*/

/** @todo Put code from #226 in here */
// @todo Reduce duplication in money calculation and formatting
const toMoneyStr = function (decimal) {
return (decimal).toFixed(2);
};
Expand Down
59 changes: 35 additions & 24 deletions src/utils/registerServiceWorker.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,17 @@
// This link also includes instructions on opting out of this behavior.

const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
window.location.hostname === `localhost` ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
window.location.hostname === `[::1]` ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);

export default function register() {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
const registerServiceWorker = function () {
if (process.env.NODE_ENV === `production` && `serviceWorker` in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
if (publicUrl.origin !== window.location.origin) {
Expand All @@ -31,7 +31,7 @@ export default function register() {
return;
}

window.addEventListener('load', () => {
window.addEventListener(`load`, () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

if (!isLocalhost) {
Expand All @@ -42,10 +42,11 @@ export default function register() {
checkValidServiceWorker(swUrl);
}
});
}
}
} // ends if the URL constructor is available
};


function registerValidSW(swUrl) {
const registerValidSW = function (swUrl) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
Expand All @@ -58,30 +59,31 @@ function registerValidSW(swUrl) {
// the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
console.log('New content is available; please refresh.');
console.log(`New content is available; please refresh.`);
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
console.log(`Content is cached for offline use.`);
}
}
};
};
})
}) // ends then register
.catch(error => {
console.error('Error during service worker registration:', error);
console.error(`Error during service worker registration:`, error);
});
}
};


function checkValidServiceWorker(swUrl) {
const checkValidServiceWorker = function (swUrl) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
if (
response.status === 404 ||
response.headers.get('content-type').indexOf('javascript') === -1
response.headers.get(`content-type`).indexOf(`javascript`) === -1
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
Expand All @@ -92,19 +94,28 @@ function checkValidServiceWorker(swUrl) {
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl);
}
})
} // ends if service worker exists
}) // ends fetch response
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
`No internet connection found. App is running in offline mode.`
);
});
}

export function unregister() {
if ('serviceWorker' in navigator) {

const unregister = function () {
if (`serviceWorker` in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
};


export {
registerServiceWorker,
registerValidSW,
checkValidServiceWorker,
unregister,
}
18 changes: 10 additions & 8 deletions src/utils/setNestedProperty.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { valueFixers } from './valueFixers';
import { getSideEffects } from './getSideEffects';


const setNestedProperty = function ({ route, value, time }, { current, future }, previouslySetByUser) {

let itemID = route.shift();
Expand All @@ -20,38 +21,39 @@ const setNestedProperty = function ({ route, value, time }, { current, future },
};
setNestedProperty({ route, value, time }, next, previouslySetByUser);
applySideEffects({ current, future, itemID });
}
} // ends if last recursion because route is empty

}; // End setNestedProperty()
};


const setValidCurrent = function ({ name, value, type }, newCurrent) {
if (type === 'current') {
if (type === `current`) {
newCurrent[ name ] = valueFixers[ name ](value, newCurrent);
}

return newCurrent;
}; // End setValidCurrent()
};


const setValidFuture = function (evnt, newFuture, setByUser) {

let newValue = valueFixers[ evnt.name ](evnt.value, newFuture);

if (evnt.type === 'future') {
if (evnt.type === `future`) {
newFuture[ evnt.name ] = newValue;

} else if (evnt.type === 'current') {
} else if (evnt.type === `current`) {
// If this 'future' value hasn't been changed by the user
// then it continue to be synched up with the 'current'
// value.
if (!setByUser) {
newFuture[ evnt.name ] = newValue;
}
}
} // ends if which part of the client object

return newFuture;
}; // End setValidFuture()
};


/** Trigger functions that could affect other client
* values. Run after other client properties have
Expand Down
6 changes: 3 additions & 3 deletions src/utils/validators.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@ const hasOnlyNonNegWholeNumberChars = function (str) {
};

/** Returns true if a string represents a positve number (integer or float) */
// Should this only be valid if it has <= 2 decimal places?
const isNonNegNumber = function (str) {
// Should this only be valid if it has <= 2 decimal places?
return str !== '' && !/[^0-9.]|\..*\./.test(str);
};


/** Returns true if a string represents a positive integer */
/** @todo Change name to 'isWholeNumber'. */
const isNonNegWholeNumber = function (str) {
// @todo Change name to 'isWholeNumber'.
return str !== '' && /^[0-9]*$/.test(str);
};

Expand Down Expand Up @@ -68,7 +68,7 @@ const isNumberlike = function (numberOrString) {
return new TypeError(`Expected 'numberOrString' to be a number or string that can be converted to a number and it was ${numberOrString}.`);
}

};
}; // Ends isNumberlike()


export {
Expand Down
Loading

0 comments on commit d2ae9d3

Please sign in to comment.