Best way to move an item to the start of a collection

Viewed 304

If I have a collection

let initial = [ "a", "b", "c", "d", "e" ]

and I wanted to move an item from that collection to the start (but keep the ordering of the other items intact)

let final = initial.placeFirst { $0 == "b" }
assert(final == [ "b", "a", "c", "d", "e" ])

What would be the best way to implement placeFirst?

My example has the elements as Equatable - that's just to make the question readable, it's sadly not the case in real life, hence a predicate passed into placeFirst which will return true for the item I want at the start.

For my use case there should only be one item which matches the predicate - if more than one matches then putting any (or some, or all) of the matching elements at the start is fine.

I have a few ideas, but it seems like the kind of problem there would be a really neat solution which uses bits of Collection/Sequence I'm not aware of yet.

PS I do realize how much this sounds like a homework question - I promise it's not :)

2 Answers
Related