Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

aleksandra.valchanova avatar aleksandra.valchanova 0 Точки

String Extention

Здравейте, 

Решила съм задачата на г/д 80%, но с последния метод, който трябва да е статичен, не знам как да се справя. Разписала съм я цялата, като format(), също съм го разписала поне като функционалност с тази грешка, че не е статичен метод, а обикновен. 

Решението:

https://pastebin.com/C75xnUgp?fbclid=IwAR2i4I5t9BSg5_gX9FneVlLdwKtUsrmi63CegEyI-9FUAAbd4rSpvD7gZBE

Условието:

Extend the built-in String object with additional functionality. Implement the following functions:

  • ensureStart(str) – if the current string doesn't start with the str parameter, return a new string in which str parameter appended to the beginning of the current string, otherwise returns the original string
  • ensureEnd(str) – if the current string doesn't end with str parameter, return a new string in which str parameter appended to the end of the current string, otherwise returns the original string
  • isEmpty() - return true if the string is empty and false otherwise
  • truncate(n) – returns the string truncated to n characters by removing words and appends an ellipsis (three periods) to the end. If a string is less than n characters long, return the same string. If it is longer, split the string where a space occurs and append an ellipsis to it so that the total length is less than or equal to n. If no space occurs anywhere in the string, return n - 3 characters and an ellipsis. If n is less than 4, return n amount of periods.
  • format(string, …params) - static method to replace placeholders with parameters. A placeholder is a number surrounded by curly braces. If parameter index cannot be found for a certain placeholder, do not modify it. Note static methods are attached to the String object instead of its prototype. See the examples for more info.

Note strings are immutable, so your functions will return new strings as a result.

Input / Output

Your main code should be structured as an IIFE without input or output - it should modify the existing String prototype instead.

Input and output of the extension functions should be as described above.

Input: 

let str = 'my string';

str = str.ensureStart('my');

str = str.ensureStart('hello ');

str = str.truncate(16);

str = str.truncate(14);

str = str.truncate(8);

str = str.truncate(4);

str = str.truncate(2);

str = String.format('The {0} {1} fox',

  'quick', 'brown');

str = String.format('jumps {0} {1}',

  'dog');

 

Expected Output:

'my string'   

'hello my string'

'hello my string' 

'hello my...' 

'hello...'

'h...'

'..'

 

'The quick brown fox'

'jumps dog {1}'  

Тагове:
0
Module: JS Advanced
Axiomatik avatar Axiomatik 2422 Точки

Nice code, for static method just use String.format instead of String.prototype.format.

More compact demo code =>

(function () {
    String.prototype.ensureStart = function (str) {
        // if (this.slice(0, str.length) === str) {
        if (this.startsWith(str)) {
            return this.toString();
        }
        return `${str}${this}`;
    };

    String.prototype.ensureEnd = function (str) {
        if (this.endsWith(str)) {
            return this.toString();
        }
        return `${this}${str}`;
    };

    String.prototype.isEmpty = function () {
        return this.toString() === '';
    };

    String.prototype.truncate = function (n) {
        if (this.length <= n) {
            return this.toString();
        }

        if (this.includes(' ')) {
            let lastSpaceIndex = this.length;
            do {
                lastSpaceIndex = this.lastIndexOf(' ', lastSpaceIndex - 1);
            } while (lastSpaceIndex !== -1 && lastSpaceIndex + 3 > n)
            return `${this.slice(0, lastSpaceIndex)}...`;
        }

        if (n > 3) {
            let string = `${this.slice(0, n - 3)}...`;
            return string;
        }
        return '.'.repeat(n);
    };

    String.format = function (string, ...params) {
        let replaceRegex = /{(\d+)}/g;
        let replaced = string.replace(replaceRegex, (match, group1) => {
            let index = Number(group1);
            if (params[index] !== undefined) {
                return params[index];
            }

            return match;
        });

        return replaced;
    };
}())

;-)

0
Mights00 avatar Mights00 -1 Точки

Thanks for sharing this useful code. Have a nice day playing geometry dash. A fast-paced game that helps you activate your brain quickly.

-1
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.