Skip to content

Commit

Permalink
feat: makeKeyGeneric supports $[] as positional operator (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
kfritsch authored Apr 18, 2021
1 parent e19cbbd commit 67507c3
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
9 changes: 5 additions & 4 deletions lib/mongo-object.js
Original file line number Diff line number Diff line change
Expand Up @@ -671,16 +671,17 @@ export default class MongoObject {

/* STATIC */

/* Takes a specific string that uses mongo-style dot notation
* and returns a generic string equivalent. Replaces all numeric
* "pieces" with a dollar sign ($).
/* Takes a specific string that uses any mongo-style positional update
* dot notation and returns a generic string equivalent. Replaces all numeric
* positional "pieces" (e.g. '.1') or any other positional operator
* (e.g. '$[<identifier>]') with a dollar sign ($).
*
* @param {type} name
* @returns {String} Generic name.
*/
static makeKeyGeneric(key) {
if (typeof key !== 'string') return null;
return key.replace(/\.[0-9]+(?=\.|$)/g, '.$');
return key.replace(/\.([0-9]+|\$\[[^\]]*\])(?=\.|$)/g, '.$');
}

/** Takes a string representation of an object key and its value
Expand Down
14 changes: 12 additions & 2 deletions lib/mongo-object.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -201,8 +201,18 @@ describe('MongoObject', () => {
});

it('makeKeyGeneric', () => {
const generic = MongoObject.makeKeyGeneric('foo.0.0.ab.c.123.4square.d.67e.f.g.1');
expect(generic).toEqual('foo.$.$.ab.c.$.4square.d.67e.f.g.$');
function testMakeKeyGeneric(input, expectedOutput) {
const generic = MongoObject.makeKeyGeneric(input);
expect(generic).toEqual(expectedOutput);
}
testMakeKeyGeneric(0, null);
testMakeKeyGeneric({}, null);
testMakeKeyGeneric('foo', 'foo');
testMakeKeyGeneric('foo.bar', 'foo.bar');
testMakeKeyGeneric('foo.$', 'foo.$');
testMakeKeyGeneric('foo.0.0.ab.c.123.4square.d.67e.f.g.1', 'foo.$.$.ab.c.$.4square.d.67e.f.g.$');
testMakeKeyGeneric('foo.$[].foo.$[bar].$.$[]', 'foo.$.foo.$.$.$');
testMakeKeyGeneric('foo.$foo.$foo[bar]foo.foo$[].foo$[bar]', 'foo.$foo.$foo[bar]foo.foo$[].foo$[bar]');
});

it('cleanNulls', () => {
Expand Down

0 comments on commit 67507c3

Please sign in to comment.