Skip to content

Instantly share code, notes, and snippets.

@tracker1
Created February 9, 2017 01:11
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tracker1/e894bb98f6a92dad76849098f90c911d to your computer and use it in GitHub Desktop.
Save tracker1/e894bb98f6a92dad76849098f90c911d to your computer and use it in GitHub Desktop.
prehash password
export default function normalizeToString(input) {
// string or String object
if (typeof input === 'string' || input instanceof String) return input.toString();
// boolean value
if (typeof input === 'boolean') return input.toString();
// numeric value
if (typeof input === 'number' || input instanceof Number) {
// not a finite value - invalid input - return empty
if (!Number.isFinite(input)) return '';
// safe integer, return as-is
if (Number.isSafeInteger(input)) return input.toString(10);
// not a safe integer, return with 5 decimal places
return input.toFixed(5); // fix to 4 decimal places
}
// if there's a JSON method, use the result of that
if (typeof input.toJSON === 'function') {
const ret = input.toJSON();
if (typeof ret === 'string') return ret;
}
// unsupported value - empty string
return '';
}
import normalizeToString from './normalize-to-string';
export default function normalizeKeyValue(input) {
let result = normalizeToString(input);
// no input
if (!result) return '';
// input too long - can cause regex issues down below
if (result.length > 1024) return '';
// normalize unicode - ensure input will always be in the same structure
result = result.normalize('NFKC');
// replace all whitespace characters with space
// eslint-disable-next-line no-irregular-whitespace
result = result.replace(/[ \f\n\r\t\v\u00A0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u2028\u2029\u202f\u205f\u3000]/g, ' ');
// trim - handle copy-paste issues
result = result.trim();
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment