Skip to content

Commit 6f1462f

Browse files
committed
add function to objectify input
1 parent 48bf789 commit 6f1462f

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

packages/utils/src/object.ts

+32
Original file line numberDiff line numberDiff line change
@@ -398,3 +398,35 @@ export function dropUndefinedKeys<T>(val: T): T {
398398

399399
return val;
400400
}
401+
402+
/**
403+
* Ensure that something is an object.
404+
*
405+
* Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper
406+
* classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.
407+
*
408+
* @param wat The subject of the objectification
409+
* @returns A version of "wat` which can safely be used with `Object` class methods
410+
*/
411+
export function objectify(wat: unknown): typeof Object {
412+
let objectified;
413+
switch (true) {
414+
case wat === undefined || wat === null:
415+
objectified = new String(wat);
416+
break;
417+
418+
case typeof wat === 'symbol' || typeof wat === 'bigint':
419+
objectified = Object(wat);
420+
break;
421+
422+
case isPrimitive(wat):
423+
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
424+
objectified = new (wat as any).constructor(wat);
425+
break;
426+
427+
default:
428+
objectified = wat;
429+
break;
430+
}
431+
return objectified;
432+
}

0 commit comments

Comments
 (0)