팡이네

typescript, angular

 

문자열 표시 파이프

//--------------------------------------
// 문자열 표시 파이프
//--------------------------------------
/**
 * 문자열 형식 표시
 * options {
 *     replace: %s를 문자열로 변환하여 표시,
 *     pre:  문자열 앞에 표시
 *     post: 문자열 뒤에 표시
 *     limit: 지정한 길이만큼 표시
 * }
 * 사용법)
 *     {{ null | string : { post: '년' } }} => null
 *     {{ '2021' | string : { post: '년' } }} => '2021년'
 *     {{ '2021' | string : { replace: '(%s년 리모델링)' } }} => '(2021년 리모델링)'
 *     {{ 25 | string : { replace: '(지상 %s층)' } }} {{ 8 | string : { replace: ' / 지하 %s층' } }} => '지상 25층 / 지하 8층'
 *     {{ 25 | string : { replace: '(지상 %s층)' } }} {{ null | string : { replace: ' / 지하 %s층' } }} => '지상 25층'
 */
@Pipe({ name: 'string' })
export class StringPipe implements PipeTransform {
    transform(value: number | string, options?: { replace: string, pre: string, post: string, limit: number }): string {
        if (value) {
            let result: string = null;
            if (options?.replace) {
                result = options?.replace.replace('%s', ''+ value);
            } else {
                result = ((options?.pre) ? options?.pre : '') + value + ((options?.post) ? options?.post : '');
            }
            
            if (options.limit && result.length > options.limit) {
                result = result.slice(0, options.limit) +'...';
            }
            return result;
        } else {
            return null;
        }
    }
}