Skip to content

Commit

Permalink
Add string methods to prototype
Browse files Browse the repository at this point in the history
  • Loading branch information
ellatrix committed Aug 13, 2022
1 parent 9d8de32 commit 4c4f40d
Showing 1 changed file with 41 additions and 30 deletions.
71 changes: 41 additions & 30 deletions packages/rich-text/src/value.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,45 +4,56 @@
import { toHTMLString } from './to-html-string';

export class RichTextValue {
constructor( args ) {
for ( const key in args.value ) {
constructor( { value, ...settings } ) {
for ( const key in value ) {
Object.defineProperty( this, key, {
value: args.value[ key ],
value: value[ key ],
enumerable: true,
} );
}

function _toHTMLString( _args ) {
if ( ! _toHTMLString.cached ) {
_toHTMLString.cached = toHTMLString( _args );
}
return _toHTMLString.cached;
for ( const key in settings ) {
Object.defineProperty( this, key, {
value: settings[ key ],
} );
}
}

Object.getOwnPropertyNames( String.prototype )
.filter(
( prop ) =>
typeof String.prototype[ prop ] === 'function' &&
prop !== 'constructor'
)
.forEach( ( method ) => {
Object.defineProperty( this, method, {
value() {
return _toHTMLString( args )[ method ]( ...arguments );
},
} );
toString() {
if ( ! this.toString.cached ) {
this.toString.cached = toHTMLString( {
value: { ...this },
multilineTag: this.multilineTag,
preserveWhiteSpace: this.preserveWhiteSpace,
} );
}
return this.toString.cached;
}
}

Object.defineProperty( this, 'length', {
get() {
return _toHTMLString( args ).length;
},
} );

Object.defineProperty( this, 'toJSON', {
Object.getOwnPropertyNames( String.prototype )
.filter(
( prop ) =>
typeof String.prototype[ prop ] === 'function' &&
prop !== 'constructor' &&
prop !== 'toString'
)
.forEach( ( method ) => {
Object.defineProperty( RichTextValue.prototype, method, {
value() {
return _toHTMLString( args );
return this.toString()[ method ]( ...arguments );
},
} );
}
}
} );

Object.defineProperty( RichTextValue.prototype, 'length', {
get() {
return this.toString().length;
},
} );

Object.defineProperty( RichTextValue.prototype, 'toJSON', {
value() {
return this.toString();
},
} );

0 comments on commit 4c4f40d

Please sign in to comment.