Skip to content

Commit

Permalink
feat(tokey): adding util to convert value to a string key
Browse files Browse the repository at this point in the history
  • Loading branch information
roggervalf committed May 2, 2020
1 parent 97e60ed commit 8d19068
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/toKey.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { toKey } from './toKey';

describe('toKey', () => {
describe('when converting value to a string key', () => {
it('should get true', () => {
const symbol = Symbol(1);
expect(toKey(1)).toEqual('1');
expect(toKey(symbol)).toEqual(symbol);
expect(toKey(-0)).toEqual('-0');
});
});
});
19 changes: 19 additions & 0 deletions src/toKey.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { isSymbol } from './isSymbol';

/** Used as references for various `Number` constants. */
const INFINITY = 1 / 0;

/**
* Converts `value` to a string key if it's not a string or symbol.
*
* @private
* @param {*} value The value to inspect.
* @returns {string|symbol} Returns the key.
*/
export function toKey(value: any): string | symbol {
if (typeof value === 'string' || isSymbol(value)) {
return value;
}
const result = `${value}`;
return result === '0' && 1 / value === -INFINITY ? '-0' : result;
}

0 comments on commit 8d19068

Please sign in to comment.