diff --git a/.gitignore b/.gitignore index c2658d7..1ca9571 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ node_modules/ +npm-debug.log diff --git a/src/objectUtils.js b/src/objectUtils.js index 755f23d..601b181 100644 --- a/src/objectUtils.js +++ b/src/objectUtils.js @@ -24,3 +24,17 @@ export function assignDeep(target, source) { } return output; } + +function alphabetizeKeys(target, blacklist = []) { + const keys = Object.keys(target); + + const usableKeys = keys.filter(key => !blacklist.includes(key)); + usableKeys.sort(); + const updated = {}; + for (let i = 0; i < usableKeys.length; i++) { + updated[usableKeys[i]] = target[usableKeys[i]]; + } + return updated; +} + +export {alphabetizeKeys}; diff --git a/src/objectUtils.spec.js b/src/objectUtils.spec.js index 78927aa..5e7269e 100644 --- a/src/objectUtils.spec.js +++ b/src/objectUtils.spec.js @@ -1,5 +1,5 @@ import expect from 'expect'; -import {ensureArray} from './objectUtils'; +import {ensureArray, alphabetizeKeys} from './objectUtils'; describe('ensureArray', () => { it('should put object in array', () => { @@ -16,3 +16,30 @@ describe('ensureArray', () => { expect(ensureArray([obj])).toEqual([obj]); }); }); + + describe('alphabetizeKeys', () => { + it('should alphabetize keys', () => { + const original = { + name: 'joe', + age: 35 + } + const expected = { + age: 35, + name: 'joe' + } + expect(alphabetizeKeys(original)).toEqual(expected); + }) + + it('should remove blacklist', () => { + const original = { + name: 'joe', + ugliness: 'high', + age: 35 + } + const expected = { + age: 35, + name: 'joe' + } + expect(alphabetizeKeys(original, 'ugliness')).toEqual(expected); + }) + })