Skip to content

Commit

Permalink
fix: prototypal inheritance
Browse files Browse the repository at this point in the history
  • Loading branch information
MikeIbberson committed Feb 14, 2020
1 parent 8a5d4fb commit 02a3cc9
Showing 1 changed file with 49 additions and 42 deletions.
91 changes: 49 additions & 42 deletions src/parameters.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable func-names */
import flat from 'flat';
import {
isEmpty,
Expand All @@ -6,51 +7,57 @@ import {
asInverted,
} from './utils';

export default class extends URLSearchParams {
populate(a = {}) {
return Object.entries(a).reduce(
(acc, [key, value]) =>
Object.assign(acc, {
[key]: Array.isArray(value)
? this.getAll(`${key}[]`)
: this.get(key) || value,
}),
{},
);
/**
* @NOTE
* Class inheritance was not working in production envs
* Prototypes seem to register more consistently.
*/

URLSearchParams.prototype.populate = function(a = {}) {
return Object.entries(a).reduce(
(acc, [key, value]) =>
Object.assign(acc, {
[key]: Array.isArray(value)
? this.getAll(`${key}[]`)
: this.get(key) || value,
}),
{},
);
};

URLSearchParams.prototype.serializeAndAssign = function(
key,
v,
) {
const arr = serializeArray(v);
if (arr.length) {
this.set(asInverted(key, arr), asEmpty(arr));
} else {
this.delete(key);
}
};

serializeAndAssign(key, v) {
const arr = serializeArray(v);
if (arr.length) {
this.set(asInverted(key, arr), asEmpty(arr));
} else {
URLSearchParams.prototype.merge = function(a) {
Object.entries(a).forEach(([key, v]) => {
if (isEmpty(v)) {
this.delete(key);
} else if (Array.isArray(v)) {
this.serializeAndAssign(key, v);
} else if (typeof v === 'object') {
Object.entries(flat(v, { safe: true })).forEach(
([name, value]) => {
this.serializeAndAssign(`${key}.${name}`, value);
},
);
} else {
this.set(asInverted(key, v), asEmpty(v));
}
}
});
};

merge(a) {
Object.entries(a).forEach(([key, v]) => {
if (isEmpty(v)) {
this.delete(key);
} else if (Array.isArray(v)) {
this.serializeAndAssign(key, v);
} else if (typeof v === 'object') {
Object.entries(flat(v, { safe: true })).forEach(
([name, value]) => {
this.serializeAndAssign(
`${key}.${name}`,
value,
);
},
);
} else {
this.set(asInverted(key, v), asEmpty(v));
}
});
}
URLSearchParams.prototype.redirectStr = function() {
const str = this.toString();
return str ? `?${str}` : '?';
};

redirectStr() {
const str = this.toString();
return str ? `?${str}` : '?';
}
}
export default URLSearchParams;

0 comments on commit 02a3cc9

Please sign in to comment.