phpify/string/implode.rs
1// Copyright (c) 2020 DarkWeb Design
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
11// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
13// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
14// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
15// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
16// SOFTWARE.
17
18// https://www.php.net/manual/en/ref.strings.php
19
20/// Join vec elements with a string.
21///
22/// # Description
23///
24/// Join vec elements with a glue string.
25///
26/// # Examples
27///
28/// Example #1 implode() example
29///
30/// ```
31/// use phpify::string::implode;
32///
33/// let vec = vec!["lastname".to_string(), "email".to_string(), "phone".to_string()];
34/// let comma_separated = implode(",", &vec);
35///
36/// assert_eq!(comma_separated, "lastname,email,phone");
37/// ```
38pub fn implode<G>(glue: G, pieces: &Vec<String>) -> String
39 where
40 G: AsRef<str> {
41
42 pieces.join(glue.as_ref())
43}
44
45#[cfg(test)]
46mod tests {
47 use crate::string::implode;
48
49 #[test]
50 fn test() {
51 assert_eq!(implode("|", &vec!["one".to_string(), "two".to_string(), "three".to_string()]), "one|two|three".to_string());
52 assert_eq!(implode("", &vec!["one".to_string(), "two".to_string(), "three".to_string()]), "onetwothree".to_string());
53 assert_eq!(implode("", &vec![]), "".to_string());
54 }
55}