File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change @@ -398,3 +398,39 @@ 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+ // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason
419+ // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as
420+ // an object in order to wrap it.
421+ case typeof wat === 'symbol' || typeof wat === 'bigint' :
422+ objectified = Object ( wat ) ;
423+ break ;
424+
425+ // this will catch the remaining primitives: `String`, `Number`, and `Boolean`
426+ case isPrimitive ( wat ) :
427+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
428+ objectified = new ( wat as any ) . constructor ( wat ) ;
429+ break ;
430+
431+ default :
432+ objectified = wat ;
433+ break ;
434+ }
435+ return objectified ;
436+ }
You can’t perform that action at this time.
0 commit comments