Skip to content
This repository has been archived by the owner on Dec 15, 2021. It is now read-only.

Commit

Permalink
feat(keys): Add module keys
Browse files Browse the repository at this point in the history
Returns an array of keys of an object
  • Loading branch information
adambrgmn committed Jan 16, 2018
1 parent 23e084a commit c10fa0e
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 1 deletion.
9 changes: 9 additions & 0 deletions src/__tests__/keys.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import keys, { _keys } from '../keys';

test('Core.keys', () => {
expect(keys({ a: 1, b: 2 })).toEqual(['a', 'b']);
});

test('Internal._keys', () => {
expect(_keys({ a: 1, b: 2 })).toEqual(['a', 'b']);
});
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import isNumber from './isNumber';
import isObject from './isObject';
import isString from './isString';
import join from './join';
import keys from './keys';
import last from './last';
import length from './length';
import map from './map';
Expand Down Expand Up @@ -64,6 +65,7 @@ export {
isObject,
isString,
join,
keys,
last,
length,
map,
Expand Down
45 changes: 45 additions & 0 deletions src/keys.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/* eslint-disable no-underscore-dangle, no-restricted-syntax */
import isObject from './isObject';
import has from './has';
import length from './length';
import nth from './nth';

export const _keys = obj => {
const hasDontEnumBug = !Object.prototype.propertyIsEnumerable.call(
{ toString: null },
'toString',
);

const dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor',
];

const dontEnumsLength = length(dontEnums);

if (!isObject(obj)) throw new TypeError('Keys called on non-object');

const result = [];

for (const prop in obj) {
if (has(prop, obj)) result.push(prop);
}

if (hasDontEnumBug) {
for (let i = 0; i < dontEnumsLength; i++) {
const prop = nth(i, dontEnums);
if (has(prop, obj)) {
result.push(prop);
}
}
}

return result;
};

export default Object.keys || _keys;
3 changes: 2 additions & 1 deletion src/map.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ import isObject from './isObject';
import assoc from './assoc';
import append from './append';
import prop from './prop';
import keys from './keys';

export default (fn, arr) => {
if (isObject(arr)) {
return reduce(
(acc, key) => assoc(key, fn(prop(key, arr)), acc),
{},
Object.keys(arr),
keys(arr),
);
}

Expand Down

0 comments on commit c10fa0e

Please sign in to comment.