• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Get all but last element in TypeScript

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
I wrote this content originally on my website :

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Whereas the answer is initially pretty straightforward, this blog article is mostly for beginners, and how to think about code readability for others.

Here is the article :

What if you want to get all elements but the last one inside an array in TypeScript ?

Well, it's a JS feature, that should be relevant in any environment.

Naïve answer


The answer is


// remove only the last element of array a
let b = a.slice(0, -1);
// a is left as-is
// b is all but the last element

A more complete TS example would be


const a: number[] = [1, 2, 3, 4];
const result = a.slice(0, -1);
console.log(result); // Will output [1, 2, 3]
console.log(a); // Will output [1, 2, 3, 4]

However, I'm not 100% satisfied with that.

It works, and has no side-effect, which means you can confidently pipe the output.

But it's not very readable.

Code for others


There is no a.getAllButLastElement, which would be a lot more convenient to read (and to remember!)

So if you want to avoid over-engineering, you have no other option than commenting directly the code :


const a: number[] = [1, 2, 3, 4];
const result = a.slice(0, -1); // remove last elt only
console.log(result);
console.log(a);

Mmh works, it is readable, but I'm still not 100% satisfied with that.

It's not re-usable accross the project

Reusable all but last in TypeScript


So finally I would use something like this :


function allButLast<T>(arr: T[]): T[] {
return arr.slice(0, -1);
}

const a: number[] = [1, 2, 3, 4];

const result = allButLast(a);

console.log(result);
console.log(a);

Good!

Now this is reusable, and self-documented.

Summary


So that's it for today, solve this was not a big deal, but you can notice how to tackle elegantly a simple problem on real-world projects.

Best,

David


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу