[Question]
  [
# [Garland Words](http://blog.vivekhaldar.com/post/89763722591/garland-words)
A *garland word* is a word which can be strung together like a garland, because it ends with the same letters it starts with. These groups of letters can even overlap! 
For example, `underground` is a garland word of order `3`, because it starts and end with the same 3 characters, `und`. This means it could be strung together like `undergroundergrounderground...`.
`alfalfa` is a garland word, too! It's of order 4. It starts and ends with `alfa`. It can be strung together like so: `alfalfalfalfa`.
A process which I call garlandifying is where once you determine the order `n` of a garland word, you take the original word and add the segment required to have it loop as a garland `n` times. So, since `onion` is an order `2` garland word, you would take `onion`, chop off the first `2` letters to get `ion` and add that to the end `2` times to get `onionionion`.
# Objective
Make a *program or function* which takes input from **standard input or a function argument** and prints out or returns the word, garlandified.
All words will be lowercase, and the highest possible order for a word is `length(word) - 1`.
# Example I/O
```
"onion"       --> "onionionion"
"jackhammer"  --> "jackhammer"
"abracadabra" --> "abracadabracadabracadabracadabracadabra"
""            --> ""
"zvioz"       --> "zviozvioz"
"alfalfa"     --> "alfalfalfalfalfalfa"
"aaaa"        --> "aaaaaaa"
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so least number of bytes wins.
  
[Answer]
# Python, 60 bytes
```
f=lambda s,i=1:s.find(s[i:])and f(s,i+1)or(len(s)-i)*s[:i]+s
```
Was hoping for better, but oh well. `s.find` works neatly here in place of `not s.startswith`.
[Answer]
# Pyth, ~~19~~ 18 bytes
```
+z*>Kf!xz>zT1zl>zK
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=%2Bz*%3EKf!xz%3EzT1zl%3EzK&input=abracadabra&debug=0) or [Test harness](http://pyth.herokuapp.com/?code=zFz.zp%60zp%22+-%3E+%22%60%0A%2Bz*%3EKf!xz%3EzT1zl%3EzK&input=Test-cases%3A%0Aonion%0Ajackhammer%0Aabracadabra%0A%0Azvioz%0Aalfalfa%0Aaaaa&debug=0)
### Explanations:
```
+z*>Kf!xz>zT1zl>zK   implicit: z = input string
     f      1        find the first number T >= 1, which satisfies:
         >zT            all but the first T chars of z
       xz               index of ^ in z
      !                 == 0
    K                store in K
                     the order is length(z) - K
   >K        z       the last K chars
  *                  repeated
              l>zK   len(all but the last K chars) times
+z                   insert z at the beginning
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), 58 bytes
```
.+
$0#$0
(.*)(.+)#.*\1$
$0#$1#$2-
+`\w#(\w*)-
#$1-$1
#.*-
<empty line>
```
Each line should go to its own file but you can run the code as one file with the `-s` flag.
The four substitution pairs do the followings:
* Duplicate word so we can search for overlaps too.
* Append the word split up at `order` number of characters.
* Append the last part `order` times.
* Keep the original word and the lastly appended part and drop everything else.
The string states for the example `onion`:
```
onion
onion#onion
onion#onion#on#ion-
onion#onion##ion-ionion
onionionion
```
[Answer]
## Haskell, 64 bytes
```
g s=[b>>a|(a,b)<-map(`splitAt`s)[1..],and$zipWith(==)s b]!!0++s
```
Tests:
```
λ: g "onion"       == "onionionion"
True
λ: g "jackhammer"  == "jackhammer"
True
λ: g "abracadabra" == "abracadabracadabracadabracadabracadabra"
True
λ: g ""            == ""
True
λ: g "zvioz"       == "zviozvioz"
True
λ: g "alfalfa"     == "alfalfalfalfalfalfa"
True
λ: g "aaaa"        == "aaaaaaa"
True
```
[Answer]
# Java, ~~160~~ 157 bytes
```
static void g(String s){int i=s.length(),o;for(String p=s;i-->0;)if(s.endsWith(s.substring(0,i))){for(o=i;o-->0;)p+=s.substring(i);System.out.print(p);i=0;}}
```
Input/Output:
```
 g("abracadabra"); --> "abracadabracadabracadabracadabracadabra"
```
Spaced and tabbed for readability:
```
static void g(String s){
int i=s.length(),o;
for(String p=s;i-->0;)
    if(s.endsWith(s.substring(0,i))){
        for(o=i;o-->0;)
            p+=s.substring(i);
        System.out.print(p);
        i=0;
    }
}
```
Suggestions welcome.
[Answer]
# Sed: ~~87~~ 84 characters
(83 characters code + 1 character command line option.)
```
h
s/(.*)./& \1/
T
s/(.+) \1.*/ \1 \1/
t
g
q
:
s/^([^ ]+)(.*)[^ ]$/\1 \1\2/
t
s/ //g
```
Sample run:
```
bash-4.3$ sed -r 'h;s/(.*)./& \1/;T;s/(.+) \1.*/ \1 \1/;t;g;q;:;s/^([^ ]+)(.*)[^ ]$/\1 \1\2/;t;s/ //g' <<< 'underground'
undergroundergroundergrounderground
```
[Answer]
# CJam, ~~24~~ 23 bytes
```
q_:Q,{~)Q>Q\#!},W>~_Q>*
q_:Q                       e# Read the input, take a copy and store it in Q too
    ,{        },           e# Take the length of the input and filter [0 .. len - 1] array
      ~)                   e# Same as number * -1
        Q>                 e# Take last number characters. Call this string S
          Q\#!             e# See if Q starts with S. After the filter, we will only have
                           e# those numbers from [0 .. len - 1] array which are valid orders
                W>~        e# Take the last order number, if exists.
                   _Q>*    e# Garlandify the input order times.
```
Just to start it with something..
[Try it online here](http://cjam.aditsu.net/#code=q_%3AQ%2C%7B~)Q%3EQ%5C%23!%7D%2CW%3E~_Q%3E*&input=alfalfa)
[Answer]
## Matlab: ~~97~~ ~~89~~ 82 bytes
Function that uses a regular expression with lookbehind and a capture group:
```
function t=f(s)
n=sum(regexp(s,'(.*$)(?<=^\1.+)'))-1;t=[s(repmat(1:n,1,end-n)) s];
```
That `sum` is needed to handle the empty-string input (convert `[]` into `0`).
Examples:
```
> f('onion'), f('jackhammer'), f('abracadabra'), f(''), f('zvioz'), f('alfalfa'), f('aaaa')
ans =
onionionion
ans =
jackhammer
ans =
abracadabracadabracadabracadabracadabra
ans =
   Empty string: 1-by-0
ans =
zviozvioz
ans =
alfalfalfalfalfalfa
ans =
aaaaaaa
```
[Answer]
# REGXY, ~~53~~ 49 bytes
Uses [REGXY](http://esolangs.org/wiki/REGXY), a regex substitution based language
```
//$'#/
/.(.+)#\1\K/#/
a/(#).(.*#)|#.*/$'$1$2/
//a
```
**Overview:**
A number of regular expressions are applied. An example run would look like:
```
onion (input)
onion#onion (line 1 regex)
onion#on#ion (line 2 regex - find the repeated section and separate with #)
onionion#n#ion (line 3 regex - the length of the middle token is the garland order, remove a character and append the third token onto the original string on the left)
onionionion##ion (line 4 regex is a pointer to line 3 - repeat the previous again)
onionionion##ion (line 4 regex is a pointer to line 3 - strip everything after and including the #)
```
**Detailed explanation**
The following is a line by line breakdown of the regexes:
```
//$'#/
```
This is a regex substitution which matches the first empty string (i.e. the start of the string) and replaces it with everything to the right of the match (`$'`) followed by a hash. For example, it will turn `onion` into `onion#onion`.
```
/.(.+)#\1\K/#/
```
This line finds the section which overlaps by looking for a group of characters immediate preceding the # (`(.+)`) which are the same on the other side of the # (`\1`). The \K just means 'forget that I matched anything', meaning it will not actually be replaced in the substitution. This effectively, this means we just add a # to the position after the overlap has been found, turning `onion#onion` into `onion#on#ion`.
```
a/(#).(.*#)|#.*/$'$1$2/
```
The initial 'a' is just a label for the regex. After this, we find the first # followed by a single character (`.`) and capture everything after this until the next # (`.*#`). We replace this with everything to the right of the match, i.e. the last token ($'), followed by a # (`$1`), followed by the second token less a character (we treat this as a counter, decreasing it each iteration). In the case of onion#on#ion, the two tokens we backreference on are shown in brackets, and the section the entire regex matches is between the pipes: `onion|(#)o(n#)|ion`. We then replace the bits we match (between the pipes) with `$'` (everything to the right of the match, i.e. 'ion'), then $1 (the #), then $2 (n#), meaning we end up with `onion|(ion)(#)(n#)|ion` (brackets show the three tokens in the replacement string).
If the regex fails to match in the first alternation (everything before the pipe), we must have decreased our counter to zero, meaning there are no characters inside the second token. Instead, we look at the second part of the pattern, `#.*`. This simply replaces everything after the first # with `$'$1$2`. Since there are no backreferences created by this alternation, and there is nothing to the right of the match (`.*` matches until the end of the string), we terminate the match and return the result.
```
//a
```
This is just a pointer to the previous line, ensuring we continue to execute the regex substitution until it fails to match any more.
[Answer]
# jq 1.5: 91 characters
(87 characters code + 4 characters command line option.)
```
.+. as$t|[range(1;length)|select($t[:.]==$t[-.:])]|(max//0)as$i|[range($i)|$t[$i:]]|add
```
Sample run:
```
bash-4.3$ jq -R -r -f judy.jq <<< 'underground'
undergroundergroundergrounderground
```
[Answer]
# [rs](https://github.com/kirbyfan64/rs), ~~51~~ 48 bytes
```
(.+)/\1 \1
(.+)(.+) .+\1$/\1(\2)^^((^^\1_))
 .*/
```
TAKE THAT, RETINA AND SED!!!!! ;)
Cut off 3 bytes thanks to @randomra.
[Live demo and test cases.](http://kirbyfan64.github.io/rs/index.html?script=(.%2B)%2F%5C1%20%5C1%0A(.%2B)(.%2B)%20.%2B%5C1%24%2F%5C1(%5C2)%5E%5E((%5E%5E%5C1_))%0A%C2%A0.*%2F&input=onion%0Ajackhammer%0Aabracadabra%0Azvioz%0Aalfalfa%0Aaaaa)
Note that the `jackhammer` test case is not there. There's a bug in the [handling of spaces in the web interface](https://github.com/kirbyfan64/rs/issues/2) that causes it to print incorrect output. The offline version of `rs` handles it correctly.
51-byte version:
```
(.+)/\1 \1
^(.+)(.+) (.+)\1$/\1(\2)^^((^^\1_))
 .*/
```
[Live demo and test cases for original.](http://kirbyfan64.github.io/rs/index.html?script=(.%2B)%2F%5C1%20%5C1%0A%5E(.%2B)(.%2B)%20(.%2B)%5C1%24%2F%5C1(%5C2)%5E%5E((%5E%5E%5C1_))%0A%C2%A0.*%2F&input=onion%0Aabracadabra%0Azvioz%0Aalfalfa%0Aaaaa)
[Answer]
## JavaScript (ES6), 95 bytes
```
f=s=>{for(e=i=s.length;i&&e;)s+=s.slice(--i).repeat(!(e=!s.endsWith(s.slice(0,i)))*i);return s}
```
### Demo
Firefox only for now:
```
f = s => {
  for (e = i = s.length; i && e;) s += s.slice(--i).repeat(!(e = !s.endsWith(s.slice(0, i))) * i);
  return s
}
console.log = x => X.innerHTML += x + '\n';
console.log(f('onion'));
console.log(f('jackhammer'));
console.log(f('abracadabra'));
console.log(f(''));
console.log(f('zvioz'));
console.log(f('alfalfa'));
console.log(f('aaaa'));
```
```
<pre id=X></pre>
```
[Answer]
## JavaScript (ES6), 82 bytes
```
g=(s,i=t=s.length)=>s.endsWith(c=s.slice(0,--i))?c+s.slice(i-t).repeat(i+1):g(s,i)
```
*[Deleted my original answer, because I've now learned ES6 and was interested in finding a recursive solution to this challenge]*
**Example**
```
g=(s,i=t=s.length)=>s.endsWith(c=s.slice(0,--i))?c+s.slice(i-t).repeat(i+1):g(s,i)
console.log(g('onion'));
console.log(g('jackhammer'));
console.log(g('abracadabra'));
console.log(g(''));
console.log(g('zvioz'));
console.log(g('alfalfa'));
console.log(g('aaaa'));
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~14~~ 13 bytes
```
ÞKvḟǓṘ†Tt~ȯẋJ
```
[Try it Online! (test suite)](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiw55LduG4n8eT4bmY4oCgVHR+yK/huotKIiwiIiwib25pb25cbmphY2toYW1tZXJcbmFicmFjYWRhYnJhXG5cbnp2aW96XG5hbGZhbGZhXG5hYWFhIl0=)
**Explanation:**
```
ÞKvḟǓṘ†Tt~ȯẋJ # whole program
ÞK            # get all suffixes of implicit input
  vḟ          # then find each first occurrence in the input 
    Ǔ         # rotate the list to the left
     Ṙ        # then reverse
      †       # logical NOT each item
       T      # get indices of elements which are truthy
        t     # get tail
          ȯ   # slice the input from it until the end 
         ~    #  just push it, do not pop the used items yet
           ẋ  # repeat the sliced input tail amount of times
            J # then join with the input
```
[Answer]
## CoffeeScript + ES6, 77 bytes
Same approach as my JavaScript answer.
```
f=(s,e=i=s.length)->s+=s[i..].repeat !(e=!s.endsWith s[...i])*i while--i&&e;s
```
[Answer]
## C
```
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv) {
    char *str   = NULL;
    char *p     = NULL;
    int len     = 0 ;
    int i       = 0;
    int j       = 0;
    int k       = 0;
    int loop    = 0;
    if (argc == 1 )
        return 0;
    str = argv[1];
    len = strlen(str);
    if (len %2) {
        loop = len/2 + 1;
    }
    else {
        loop = len/2;
    }
    p = &str[len/2];
    for (i = 0; i < loop ; i++) {
        if (str[k] == *(p++)) {
            k++;
        }
        else
            k = 0;
    }
    printf("k = %d\n", k);
    printf("%s", str);
    p = &str[k];
    for (j =0; j < k ; j++) {
        printf("%s", p);
    }
    return 0;
}
```
# Golfed: 195 bytes - GCC
```
main(int c,char**a){
char *s=a[1],*p;int i=0,j=0,k=0,z,l=strlen(a[1]);
z=l%2?-~(l/2):l/2;p=&s[l/2];
for(;i<z;i++)k=s[k]==*(p++)?-~k:0;
printf("k=%d\n",k);puts(s);p= &s[k];
for(;j<k;j++)puts(p);}
```
[Answer]
# Groovy ~~75~~ ~~57~~ 55 bytes
```
f={w->x=w;w.find{x-=it;!w.indexOf(x)};w+(w-x)*x.size()}
```
Amazing how coming back to something the day after can help
### Ungolfed:
```
f = {w ->
//Set x equal to w
    x=w
//Loop through the characters of w until we return true
    w.find {
//set x equal to x minus the first instance of the current character, i.e.     the word minus the first character
        x-=it
//Returns the index of the first occurance of the string of chars x, when this is 0 (false) we want to return true, so negate it
        !w.indexOf(x)
    }
//When we've escaped the loop, if we've found a match return the word plus the word minus the match multiplied by the lengh of the match.
    w+(w-x)*x.size()     
}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 75 bytes
```
->s{t=(1...s.size).map{s[_1..]}.find{s[/^#{_1}/]}
t ?s+s[(o=t.size)..]*o:s}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3vXXtiqtLbDUM9fT0ivWKM6tSNfVyEwuqi6PjgUKxtXppmXkpQJ5-nHJ1vGGtfmwtV4mCfbF2cbRGvm0JVINerFa-VXEt1MiygtKSYgW3aKX8vMz8PKVYLhg_KzE5OyMxNze1CEkwMakoMTkxBUQhiSIxq8oy86uQNeSkgRCyCBAoxUJsX7AAQgMA)
]