# Question
Title: Tips for Golfing in ECMAScript 6 and above
This is similar to other "Tips for golfing in \<...\>" but specifically targeting the newer features in JavaScript brought up in ECMAScript 6 and above.

JavaScript inherently is a very verbose language, `function(){}`, `.forEach()`, converting string to array, array-like object to array, etc, etc are super bloats and not healthy for Golfing.

ES6+, on the other hand, has some super handy features and reduced footprint. `x=>y`, `[...x]`, etc. are just some of the examples.

Please post some nice tricks that can help shave off those few extra bytes from your code.

**NOTE: Tricks for ES5 are already available in Tips for golfing in JavaScript; answers to this thread should focus on tricks only available in ES6 and other future ES versions.**

However, this thread is also for users who currently golf using ES5 features. Answers may also contain tips to help them understand and map ES6 features to their style of ES5 coding.

# Answer
> 57 votes
**Spread operator `...`**

The spread operator transforms an array value into a comma separated list.

Use case 1:

Directly use an array where a function expects a list

```
list=[1,2,3]
x=Math.min(...list)
list=[10,20], a.push(...list) // similar to concat()

```

Use case 2:

Create an array literal from an iterable (typically a string)

```
[...'buzzfizz'] // -> same as .split('')

```

Use case 3:

Declare a variable number of arguments for a function

```
F=(...x) => x.map(v => v+1)
// example: F(1,2,3) == [2,3,4]

```

See mozilla doc

# Answer
> 29 votes
## Using property shorthands

Property shorthands allow you to set variables to an arrays' values:

```
a=r[0];b=r[1] // ES5
[a,b]=r       // ES6 - 6 bytes saved

```

This can also be used like:

```
a=r[0],b=r[2] // ES5
[a,,b]=r      // ES6 - 5 bytes saved

```

You can even use this to reverse variables:

```
c=a,a=b,b=c // ES5 - uses extra variable
[b,a]=[a,b] // ES6 - not shorter, but more flexible

```

You can also use this to shorten `slice()` functions.

```
z = [1, 2, 3, 4, 5];

a=z.slice(1) // a = [2,3,4,5]; ES5
[,...a]=z    // a = [2,3,4,5]; ES6

```

## Base conversions

ES6 provides a much shorter way to convert form Base-2 (binary) and Base-8 (octal) to decimal:

```
0b111110111 // == 503
0o767       // == 503

```

`+` can be used to convert a binary, octal or hex string to a decimal number. You can use `0b`, `0o`, and `0x`, for binary, octal, and hex respectively.:

```
parseInt(v,2) // ES5
+('0b'+v)     // ES6 - 4 bytes saved; use '0o' for octal and '0x' for hex
'0b'+v-0      // Shorter, but may not work in all cases
              // You can adapt this your case for better results

```

---

If you are using this \> 7 times, then it will be shorter to use `parseInt` and rename it:

```
(p=parseInt)(v,2)

```

Now `p` can be used for `parseInt`, saving you many bytes over the long run.

# Answer
> 25 votes
## Tricks learned here since I joined

My primary programming language is JS and mostly ES6. Since I joined this site a week back, I have learned a lot of useful tricks from fellow members. I am combining some of those here. All credits to community.

## Arrow functions and loops

We all know that arrow functions save a lot of byts

```
function A(){do something} // from this
A=a=>do something // to this

```

But you have to keep in mind a few things

* Try to club multiple statements using `,` i.e. `(a=b,a.map(d))` \- Here, the value which is returned is the last expression `a.map(d)`
* if your `do something` part is more than one statement, then you need to add the surrounding `{}` brackets.
* If there are surrounding `{}` brackets, you need to add an explicit return statement.

The above holds true a lot of times when you have loops involved. So something like:

```
u=n=>{for(s=[,1,1],r=[i=1,l=2];c=l<n;i+=!c?s[r[l++]=i]=1:1)for(j of r)c-=j<i/2&s[i-j];return n>1?r:[1]}

```

Here I am wasting at least 9 characters due to the return. This can be optimized.

* Try to avoid for loops. Use `.map` or `.every` or `.some` instead. Note that if you want to change the same array that you are mapping over, it will fail.
* Wrap the loop in a closure arrow function, converting the main arrow function as single statement.

So the above becomes:

```
u=n=>(s=>{for(r=[i=1,l=2];c=l<n;i+=!c?s[r[l++]=i]=1:1)for(j of r)c-=j<i/2&s[i-j]})([,1,1])|n>1?r:[1]

```

removed characters: `{}return`

added characters: `(){}>|`

Note how I call the closure method, which correctly populates the variable `n` and then since the closure method is not returning anything (i.e. returning `undefined`), I bitwise or it and return the array `n` all in a single statement of the outer arrow function `u`

## Commas and semicolons

Avoid them what so ever,

If you are declaring variables in a loop, or like mentioned in the previous section, using `,` separated statements to have single statement arrow functions, then you can use some pretty nifty tricks to avoid those `,` or `;` to shave off those last few bytes.

Consider this code:

```
r=v=>Math.random()*100|0;n=r();m=r();D=v=>A(n-x)+A(m-y);d=0;do{g();l=d;d=D();....

```

Here, I am calling a lot of methods to initialize many variables. Each initialization is using a `,` or `;`. This can be rewritten as:

```
r=v=>Math.random()*100|0;n=r(m=r(d=0));D=v=>A(n-x)+A(m-y);do{d=D(l=d,g());....

```

Note how I use the fact that the method does not bother the variable passed to it and use that fact to shave 3 bytes.

## Misc

**`.search` instead of `.indexOf`**

Both give the same result, but `search` is shorter. Although search expects a Regular Expression, so use it wisely.

**\`Template Strings\`**

These are super handy when you have to concat one or more string parts based on certain conditions.

Take the following example to output a quine in JS

```
(f=x=>alert("(f="+f+")()"))()

```

vs.

```
(f=x=>alert(`(f=${f})()`))()

```

In a template string, which is a string inside two backquotes (\`), anything inside a `${ }` is treated as a code and evaluated to insert the resulting answer in the string.

I'll post a few more tricks later. Happy golfing!

# Answer
> 21 votes
## Using string templates with functions

When you have a function with one string as the arguments. You can omit the `()` if you don't have any expressions:

```
join`` // Works
join`foobar` // Works
join`${5}` // Doesn't work

```

# Answer
> 17 votes
# Array Comprehensions (Firefox 30-57)

**Note: array comprehensions were never standardized, and were made obsolete with Firefox 58. Use at your own peril.**

---

Originally, the ECMAScript 7 spec contained a bunch of new array-based features. Though most of these didn't make it into the finalized version, Firefox support(ed) possibly the biggest of these features: fancy new syntax that can replace `.filter` and `.map` with `for(a of b)` syntax. Here's an example:

```
b.filter(a=>/\s/.test(a)).map(a=>a.length)
[for(a of b)if(/\s/.test(a))a.length]

```

As you can see, the two lines are not all that different, other than the second not containing the bulky keywords and arrow functions. But this only accounts for the order`.filter().map()`; what happens if you have `.map().filter()` instead? It really depends on the situation:

```
b.map(a=>a[0]).filter(a=>a<'['&&a>'@')
[for(a of b)if(a<'['&&a>'@')a[0]]

b.map(a=>c.indexOf(a)).filter(a=>a>-1)
[for(a of b)if((d=c.indexOf(a))>-1)d]

b.map(a=>a.toString(2)).filter(a=>/01/.test(a))
[for(a of b)if(/01/.test(c=a.toString(2)))c]

```

Or what if you want *either* `.map` *or* `.filter`? Well, it usually turns out less OK:

```
b.map(a=>a.toString(2))
[for(a of b)a.toString(2)]

b.filter(a=>a%3&&a%5)
[for(a of b)if(a%3&&a%5)a]

```

So my advice is to use array comprehensions wherever you would usually use `.map` *and* `.filter`, but not just one or the other.

## String Comprehensions

A nice thing about ES7 comprehensions is that, unlike array-specific functions such as `.map` and `.filter`, they can be used on *any* iterable object, not just arrays. This is especially useful when dealing with strings. For example, if you want to run each character `c` in a string through `c.charCodeAt()`:

```
x=>[...x].map(c=>c.charCodeAt())
x=>[for(c of x)c.charCodeAt()]

```

That's two bytes saved on a fairly small scale. And what if you want to filter certain characters in a string? For example, this one keeps only capital letters:

```
x=>[...x].filter(c=>c<'['&&c>'@')
x=>[for(c of x)if(c<'['&&c>'@')c]

```

Hmm, that's not any shorter. But if we combine the two:

```
x=>[...x].filter(c=>c<'['&&c>'@').map(c=>c.charCodeAt())
x=>[for(c of x)if(c<'['&&c>'@')c.charCodeAt()]

```

Wow, a whole 10 bytes saved!

Another advantage of string comprehensions is that hardcoded strings save an extra byte, since you can omit the space after `of`:

```
x=>[...'[](){}<>'].map(c=>x.split(c).length-1)
x=>[for(c of'[](){}<>')x.split(c).length-1]

x=>[...'[](){}<>'].filter(c=>x.split(c).length>3)
x=>[for(c of'[](){}<>')if(x.split(c).length>3)c]

```

## Indexing

Array comprehensions make it a little harder to get the current index in the string/array, but it can be done:

```
a.map((x,i)=>x+i).filter ((x,i)=>~i%2)
[for(x of(i=0,a))if(++i%2)x+i-1]

```

The main thing to be careful of is to make sure the index gets incremented *every* time, not just when a condition is met.

## Generator comprehensions

Generator comprehensions have basically the same syntax as array comprehensions; just replace the brackets with parentheses:

```
x=>(for(c of x)if(c<'['&&c>'@')c.charCodeAt())

```

This creates a generator which functions in much the same way as an array, but that's a story for another answer.

## Summary

Basically, although comprehensions are usually shorter than `.map().filter()`, it all comes down to the specifics of the situation. It's best to try it both ways and see which works out better.

P.S. Feel free to suggest another comprehension-related tip or a way to improve this answer!

# Answer
> 15 votes
Function expressions in ES6 use the arrow notation, and it helps a lot saving bytes if compared with the ES5 version:

```
f=function(x,y){return x+y}
f=(x,y)=>x+y

```

If your function only has one parameter, you can omit the parentheses to save two bytes:

```
f=x=>x+1

```

If your function has no parameters at all, declare it as if it had one to save one byte:

```
f=()=>"something"
f=x=>"something"

```

Beware: Arrow functions are not exactly the same as `function () {}`. The rules for `this` are different (and better IMO). See docs

# Answer
> 15 votes
# Using `eval` for arrow functions with multiple statements and a `return`

One of the more ridiculous tricks I've stumbled across...

Imagine a simple arrow function that needs multiple statements and a `return`.

```
a=>{for(o="",i=0;i<a;i++)o+=i;return o}

```

A simple function accepting a single parameter `a`, which iterates over all integers in `[0, a)`, and tacks them onto the end of the output string `o`, which is returned. For example, calling this with `4` as the parameter would yield `0123`.

Note that this arrow function had to be wrapped in braces `{}`, and have a `return o` at the end.

This first attempt weighs in at **39 bytes**.

Not bad, but by using `eval`, we can improve this.

```
a=>eval('for(o="",i=0;i<a;i++)o+=i;o')

```

This function removed the braces and the return statement by wrapping the code in an `eval` and simply making the last statement in the `eval` evaluate to `o`. This causes the `eval` to return `o`, which in turn causes the function to return `o`, since it is now a single statement.

This improved attempt weighs in at **38 bytes**, saving one byte from the original.

But wait, there's more! Eval statements return whatever their last statement evaluated to. In this case, `o+=i` evaluates to `o`, so we don't need the `;o`! *(Thanks, edc65!)*

```
a=>eval('for(o="",i=0;i<a;i++)o+=i')

```

This final attempt weighs only **36 bytes** \- a 3 byte savings over the original!

This technique could be extended to any general case where an arrow function needs to return a value and have multiple statements (that couldn't be combined by other means)

```
b=>{statement1;statement2;return v}

```

becomes

```
b=>eval('statement1;statement2;v')

```

saving a byte.

If `statement2` evaluates to `v`, this can be

```
b=>eval('statement1;statement2')

```

saving a total of 3 bytes.

# Answer
> 12 votes
# Prefer template string new lines over "\n"

This will start to pay off at even a single new line character in your code. One use case might be:

### (16 bytes)

```
array.join("\n")

```

### (15 bytes)

```
array.join(`
`)

```

**Update:** You can even leave away the braces due to tagged template strings (thanks, edc65!):

### (13 bytes)

```
array.join`
`

```

# Answer
> 11 votes
# Returning Values in Arrow Functions

It's common knowledge that if a single statement follows the arrow function declaration, it returns the result of that statement:

```
a=>{return a+3}
a=>a+3

```

### -7 bytes

So when possible, combine multiple statements into one. This is most easily done by surrounding the statements with parentheses and separating them with commas:

```
a=>{r=0;a.map(n=>r+=n);return r}
a=>(r=0,a.map(n=>r+=n),r)

```

### -8 bytes

But if there are only two statements, it is usually possible (and shorter) to combine them with `&&` or `||`:

```
a=>{r=0;a.map(n=>r+=n);return r}

// - Use && because map always returns an array (true)
// - declaration of r moved into unused map argument to make it only 2 statements
a=>a.map(n=>r+=n,r=0)&&r

```

### -9 bytes

Finally if you are using map (or similar) and need to return a number and you can guarantee the map will never return a 1-length array with a number, you can return the number with `|`:

```
a=>{a=b=0;a.map(n=>(a+=n,b-=n));return a/b}

// - {} in map ensures it returns an array of undefined, so the | will make the returned
//   array cast from [ undefined, undefined, undefined ] to ",," to NaN to 0 and 0|n = n,
//   if the map returned [ 4 ] it would cast from [ 4 ] to "4" to 4 and make it 4|n
a=>a.map(n=>{a+=n,b-=n},a=b=0)|a/b

```

# Answer
> 10 votes
## Writing RegEx literals with `eval`

The regex constructor can be very bulky due to it's long name. Instead, write a literal with eval and backticks:

```
eval(`/<${i} [^>]+/g`)

```

If the variable `i` is equal to `foo`, this will generate:

```
/<foo [^>]+/g

```

This is equal to:

```
new RegExp("<"+i+" [^>]+","g")

```

---

You can also use `String.raw` to avoid having to repeatedly escape backslashes `\`

```
eval(String.raw`/\(?:\d{4})?\d{3}\d{3}\d{3}\d{3}\d{3}\d{3}\d{4}/g`)

```

This will output:

```
/(?:\d{4})?\d{3}\d{3}\d{3}/g

```

Which is equal to:

```
RegExp("\\(?:\\d{4})?\\d{3}\\d{3}\\d{3}\\d{3}\\d{3}\\d{3}\\d{4}","g")

```

# Keep in mind!

`String.raw` takes up a lot of bytes and unless you have at *least* nine backslashes, `String.raw` will be longer.

# Answer
> 10 votes
## Optimizing small constant ranges for `map()`

### Context

Starting with ES6, it has become fairly common to use (and abuse) the `map()` method instead of a `for` loop to iterate over a range \\$\[0..N-1\]\\$, so that the entire answer can be written in functional style:

```
for(i = 0; i < 10; i++) {
  do_something_with(i);
}

```

can be replaced by either:

```
[...Array(10).keys()].map(i => do_something_with(i))

```

or more commonly:

```
[...Array(10)].map((_, i) => do_something_with(i))

```

However, using `Array(N)` is rarely optimal when \\$N\\$ is a small constant.

### Optimizations for a range \\$\[0..N-1\]\\$, with counter

Below is a summary of shorter alternate methods when the counter \\$i\\$ is used within the callback:

```
N           | Method                               | Example                         | Length
------------+--------------------------------------+---------------------------------+-------
N ≤ 6       | use a raw array of integers          | [0,1,2,3].map(i=>F(i))          | 2N+10
N = 7       | use either a raw array of integers   | [0,1,2,3,4,5,6].map(i=>F(i))    | 24
            | or a string if your code can operate | [...'0123456'].map(i=>F(i))     | 23
            | with characters rather than integers |                                 |
8 ≤ N ≤ 9   | use scientific notation 1e[N-1]      | [...1e7+''].map((_,i)=>F(i))    | 24
N = 10      | use scientific notation 1e9          | [...1e9+''].map((_,i)=>F(i))    | 24
            | or the ES7 expression 2**29+'4' if   | [...2**29+'4'].map(i=>F(i))     | 23
            | the order doesn't matter and your    |                                 |
            | code can operate with characters     |  (order: 5,3,6,8,7,0,9,1,2,4)   |
            | rather than integers                 |                                 |
11 ≤ N ≤ 17 | use scientific notation 1e[N-1]      | [...1e12+''].map((_,i)=>F(i))   | 25
N = 18      | use the fraction 1/3                 | [...1/3+''].map((_,i)=>F(i))    | 24
N = 19      | use the fraction 1/6                 | [...1/6+''].map((_,i)=>F(i))    | 24
20 ≤ N ≤ 21 | use scientific notation 1e[N-1]      | [...1e20+''].map((_,i)=>F(i))   | 25
N = 22      | use scientific notation -1e20        | [...-1e20+''].map((_,i)=>F(i))  | 26
23 ≤ N ≤ 99 | use Array(N)                         | [...Array(23)].map((_,i)=>F(i)) | 27

```

**NB**: The length of the callback code `F(i)` is not counted.

### Optimization for the range \\$\[1..9\]\\$, with counter

If you'd like to iterate over the range \\$\[1..9\]\\$ and the order doesn't matter, you can use the following ES7 expression (provided that your code can operate with characters rather than integers):

```
[...17**6+'8'].map(i=>F(i))  // order: 2,4,1,3,7,5,6,9,8; length: 23

```

### Optimizations without counter

The following methods can be used if you just need to iterate \\$N\\$ times, without using a counter:

```
N           | Method                               | Example                         | Length
------------+--------------------------------------+---------------------------------+-------
N ≤ 5       | use a raw array of integers          | [0,0,0,0].map(_=>F())           | 2N+10
6 ≤ N ≤ 10  | use scientific notation 1e[N-1]      | [...1e7+''].map(_=>F())         | 20
11 ≤ N ≤ 17 | use scientific notation 1e[N-1]      | [...1e12+''].map(_=>F())        | 21
N = 18      | use the fraction 1/3                 | [...1/3+''].map(_=>F())         | 20
N = 19      | use the fraction 1/6                 | [...1/6+''].map(_=>F())         | 20
20 ≤ N ≤ 21 | use scientific notation 1e[N-1]      | [...1e20+''].map(_=>F())        | 21
N = 22      | use scientific notation -1e20        | [...-1e20+''].map(_=>F())       | 22
23 ≤ N ≤ 99 | use Array(N)                         | [...Array(23)].map(_=>F())      | 23

```

**NB**: The length of the callback code `F()` is not counted.

# Answer
> 10 votes
## Using `.padEnd()` instead of `.repeat()` (ES8)

Under certain circumstances, using `.padEnd()` instead of `.repeat()` saves bytes.

We can take advantage of the following properties:

* the default padding string is a single space
* when provided, the second parameter is implicitly coerced to a string

### Repeating spaces

With `.repeat()`:

```
' '.repeat(10)

```

Using `.padEnd()` saves **1 byte**:

```
''.padEnd(10)

```

Try it online!

### Repeating a dynamic value that needs to be coerced to a string

With `.repeat()`:

```
x=1;
(x+'').repeat(10)

```

Using `.padEnd()` saves **2 bytes**:

```
x=1;
''.padEnd(10,x)

```

Try it online!

# Answer
> 9 votes
# Filling Arrays - Static Values & Dynamic Ranges

I originally left these as comments under comprehensions, but since that post was primarily focused on comprehensions, I figured that it would be good to give this it's own place.

ES6 gave us the ability to fill arrays with static values without the use of loops:

```
// ES5
function(x){for(i=0,a=[];i<x;i++)a[i]=0;return a}

// ES6
x=>Array(x).fill(0)

```

Both return an array of length x, filled with the value 0.

If you want to fill arrays with dynamic values (such as a range from 0...x) however, the result is a little longer (although still shorter than the old way):

```
// ES5
function(x){for(i=0,a=[];i<x;i++)a[i]=i;return a}

// ES6
x=>Array(x).fill().map((a,i)=>i)

```

Both return an array of length x, starting with the value 0 and ending in x-1.

The reason you need the `.fill()` in there is because simply initializing an array won't let you map it. That is to say, doing `x=>Array(x).map((a,i)=>i)` will return an empty array. You can also get around the need for fill (and thus make it even shorter) by using the spread operator like so:

```
x=>[...Array(x)]

```

Using the spread operator and `.keys()` function, you can now make a short 0...x range:

```
x=>[...Array(x).keys()]

```

If you want a custom range from x...y, or a specialized range altogether (such as even numbers), you can get rid of `.keys()` and just use `.map()`, or use `.filter()`, with the spread operator:

```
// Custom range from x...y
(x,y)=>[...Array(y-x)].map(a=>x++)

// Even numbers (using map)
x=>[...Array(x/2)].map((a,i)=>i*2)

// Even numbers (using filter)
x=>[...Array(x).keys()].filter(a=>~a%2)

```

# Answer
> 9 votes
# How to golf with recursion

Recursion, though not the fastest option, is very often the shortest. Generally, recursion is shortest if the solution can simplified to the solution to a smaller part of the challenge, especially if the input is a number or a string. For instance, if `f("abcd")` can be calculated from `"a"` and `f("bcd")`, it's usually best to use recursion.

Take, for instance, factorial:

```
n=>[...Array(n).keys()].reduce((x,y)=>x*++y,1)
n=>[...Array(n)].reduce((x,_,i)=>x*++i,1)
n=>[...Array(n)].reduce(x=>x*n--,1)
n=>{for(t=1;n;)t*=n--;return t}
n=>eval("for(t=1;n;)t*=n--")
f=n=>n?n*f(n-1):1

```

In this example, recursion is obviously way shorter than any other option.

How about sum of charcodes:

```
s=>[...s].map(x=>t+=x.charCodeAt(),t=0)|t
s=>[...s].reduce((t,x)=>t+x.charCodeAt())
s=>[for(x of(t=0,s))t+=x.charCodeAt()]|t  // Firefox 30+ only
f=s=>s?s.charCodeAt()+f(s.slice(1)):0

```

This one is trickier, but we can see that when implemented correctly, recursion saves 4 bytes over `.map`.

Now let's look at the different types of recursion:

## Pre-recursion

This is usually the shortest type of recursion. The input is split into two parts `a` and `b`, and the function calculates something with `a` and `f(b)`. Going back to our factorial example:

```
f=n=>n?n*f(n-1):1

```

In this case, `a` is **n**, `b` is **n-1**, and the value returned is `a*f(b)`.

**Important note: All** recursive functions **must** have a way to stop recursing when the input is small enough. In the factorial function, this is controlled with the `n? :1`, i.e. if the input is **0**, return **1** without calling `f` again.

## Post-recursion

Post-recursion is similar to pre-recursion, but slightly different. The input is split into two parts `a` and `b`, and the function calculates something with `a`, then calls `f(b,a)`. The second argument usually has a default value (i.e. `f(a,b=1)`).

Pre-recursion is good when you need to do something special with the final result. For example, if you want the factorial of a number plus 1:

```
f=(n,p=1)=>n?f(n-1,n*p):p+1

```

Even then, however, post- is not always shorter than using pre-recursion within another function:

```
n=>(f=n=>n?n*f(n-1):1)(n)+1

```

So when is it shorter? You may notice that post-recursion in this example requires parentheses around the function arguments, while pre-recursion did not. Generally, if both solutions need parentheses around the arguments, post-recursion is around 2 bytes shorter:

```
n=>!(g=([x,...a])=>a[0]?x-a.pop()+g(a):0)(n)
f=([x,...a],n=0)=>a[0]?f(a,x-a.pop()+n):!n

```

(programs here taken from this answer)

# How to find the shortest solution

Usually the only way to find the shortest method is to try all of them. This includes:

* Loops
* `.map` (for strings, either `[...s].map` or `s.replace`; for numbers, you can create a range)
* Array comprehensions
* Pre-recursion (sometimes within another of these options)
* Post-recursion

And these are just the most common solutions; the best solution might be a combination of these, or even something entirely different. The best way to find the shortest solution is to try everything.

# Answer
> 9 votes
## Random template-string hacks

This function riffles two strings (i.e. turns `"abc","de"` into `"adbec"`):

```
f=(x,y)=>String.raw({raw:x},...y)

```

Note that this only works when `x` is longer than `y`. How does it work, you ask? `String.raw` is designed to be a template tag, like so:

```
String.raw`x: ${x}\ny: ${y}\nx + y: ${x + y}`

```

This basically calls `String.raw(["x: ", "\ny: ", "\nx + y: ", ""], x, y, x + y)`, though it's not that simple. The template array also has a special `raw` property, which is basically a copy of the array, but with the raw strings. `String.raw(x, ...args)` basically returns `x.raw[0] + args[0] + x.raw[1] + args[1] + x.raw[2] + ...` and so on until `x` runs out of items.

So now that we know how `String.raw` works, we can use it to our advantage:

```
f=(x,y)=>String.raw({raw:x},...y)                   // f("abc", "de") => "adbec"
f=x=>String.raw({raw:x},...[...x].keys())           // f("abc") => "a0b1c"
f=(x,y)=>String.raw({raw:x},...[...x].fill(y))      // f("abc", " ") => "a b c"

```

Of course, for that last one, `f=(x,y)=>x.split``.join(y)` is way shorter, but you get the idea.

Here are a couple of riffling functions that also work if `x` and `y` are of equal length:

```
f=(x,y)=>String.raw({raw:x.match(/.?/g)},...y)
f=(x,y)=>String.raw({raw:x},...y)+y.slice(-1)  // Only works if x.length == y.length

```

You can learn more about `String.raw` on MDN.

# Answer
> 8 votes
## Shorter ways to do `.replace`

---

If you want to replace all instances of one exact substring with another in a string, the obvious way would be:

```
f=s=>s.replace(/l/g,"y") // 24 bytes
f("Hello, World!")       // -> "Heyyo, Woryd!"

```

However, you can do 1 byte shorter:

```
f=s=>s.split`l`.join`y`  // 23 bytes
f("Hello, World!")       // -> "Heyyo, Woryd!"

```

Note that this is no longer shorter if you want to use any regex features besides the `g` flag. However, if you're replacing all instances of a variable, it's usually far shorter:

```
f=(s,c)=>s.replace(RegExp(c,"g"),"") // 36 bytes
f=(s,c)=>s.split(c).join``           // 26 bytes
f("Hello, World!","l") // -> "Heo, Word!"

```

---

Sometimes you'll want to map over each char in a string, replacing each one with something else. I often find myself doing this:

```
f=s=>s.split``.map(x=>x+x).join`` // 33 bytes
f=s=>[...s].map(x=>x+x).join``    // 30 bytes
f("abc") // -> "aabbcc"

```

However, `.replace` is almost always shorter:

```
f=s=>s.replace(/./g,x=>x+x)  // 27 bytes
f=s=>s.replace(/./g,"$&$&")  // Also works in this particular case

```

Now, if you want to map over each char in a string but don't care about the resulting string, `.map` is usually better because you can get rid of `.join```:

```
f=s=>s.replace(/./g,x=>t+=+x,t=0)&&t // 36 bytes
f=s=>[...s].map(x=>t+=+x,t=0)&&t     // 32 bytes
f("12345")  // -> 15

```

# Answer
> 7 votes
# `.forEach` vs `for` loops

Always prefer `.map` to any for loop. Easy, instant savings.

---

```
a.map(f)
for(x of a)f(x);
for(i=0;i<a.length;)f(a[i++]);

```
* **8 bytes total** for original
* **8 bytes saved** vs for-of (**50%** reduction)
* **22 bytes saved** vs C-style for loop (**73%** reduction)

---

```
a.map(x=>f(x,0))
for(x of a)f(x,0);
for(i=0;i<a.length;)f(a[i++],0);

```
* **16 bytes total** for original
* **2 bytes saved** vs for-of (**11%** reduction)
* **16 bytes saved** vs C-style for loop (**50%** reduction)

---

```
a.map((x,i)=>f(x,i,0))
for(i in a)f(a[i],i,0);
for(i=0;i<a.length;)f(a[i],i++,0);

```
* **22 bytes total** for original
* **1 byte saved** vs for-in (**4%** reduction)
* **11 bytes saved** vs C-style for loop (**33%** reduction)

---

```
a.map(x=>f(x)&g(x))
for(x of a)f(x),g(x);
for(i=0;i<a.length;)f(x=a[i++]),g(x);

```
* **19 bytes total** for original
* **2 bytes saved** vs for-of (**10%** reduction)
* **18 bytes saved** vs C-style for loop (**49%** reduction)

# Answer
> 7 votes
## ES6 functions

### Math

`Math.cbrt(x)` saves characters than `Math.pow(x,1/3)`, however this is obsolete when using `x**1/3`.

```
Math.cbrt(x)
Math.pow(x,1/3)

```

3 chars saved

`Math.hypot(...args)` is useful when you need the square root of the sum of the squares of the args. Making ES6 code to do that is generally much longer than using a built-in, although it can differ depending on your output format.

The function `Math.trunc(x)` wouldn't be helpful, as `x|0` is shorter. (Thanks Mwr247!)

There are many properties that take lots of code to do in ES5, but easier in ES6:

* `Math.acosh`, `asinh`, `atanh`, `cosh`, `sinh`, `tanh`. Calculates the hyperbolic equivalent of trigonometric functions, but are almost never used, except very occasionally.
* `Math.clz32`. Might be possible to do in ES5, but is easier now. Counts leading zeros in the 32-bit representation of a number.

There are a lot more, so I'm just going to list some:
`Math.sign` (occasionally useful), `Math.fround` (useless), `Math.imul` (useless), `Math.log10` (sometimes shorter than length), `Math.log2` (very useful), `Math.log1p` (almost completely useless).

# Answer
> 7 votes
## Using uninitialized counters in recursion

***Note**: Strictly speaking, this is not specific to ES6. It makes more sense to use and abuse recursion in ES6, however, because of the concise nature of arrow functions.*

---

It is rather common to come across a recursive function that's using a counter `k` initially set to zero and incremented at each iteration:

```
f = (…, k=0) => [do a recursive call with f(…, k+1)]

```

Under certain circumstances, it's possible to omit the initialization of such a counter and replace `k+1` with `-~k`:

```
f = (…, k) => [do a recursive call with f(…, -~k)]

```

This trick typically **saves 2 bytes**.

### Why and when does it work?

The formula that makes it possible is `~undefined === -1`. So, on the first iteration, `-~k` will be evaluated to `1`. On the next iterations, `-~k` is essentially equivalent to `-(-k-1)` which equals `k+1`, at least for integers in the range \[0 … 2<sup>31</sup>-1\].

You must however make sure that having `k = undefined` on the first iteration will not disrupt the behavior of the function. You should especially keep in mind that most arithmetic operations involving `undefined` will result in `NaN`.

### Example #1

Given a positive integer `n`, this function looks for the smallest integer `k` that doesn't divide `n`:

```
f=(n,k=0)=>n%k?k:f(n,k+1)   // 25 bytes

```

It can be shortened to:

```
f=(n,k)=>n%k?k:f(n,-~k)     // 23 bytes

```

This works because `n % undefined` is `NaN`, which is falsy. That's the expected result on the first iteration.

\[Link to original answer\]

### Example #2

Given a positive integer `n`, this function looks for an integer `p` such that `(3**p) - 1 == n`:

```
f=(n,p=0,k=1)=>n<k?n>k-2&&p:f(n,p+1,k*3)  // 40 bytes

```

It can be shortened to:

```
f=(n,p,k=1)=>n<k?n>k-2&&p:f(n,-~p,k*3)    // 38 bytes

```

This works because `p` is not used at all on the first iteration (`n<k` being false).

\[Link to original answer\]

# Answer
> 7 votes
## Using `flat()` when building an array recursively (ES10)

When elements are appended conditionally to an array with recursive calls, a typical construction is:

```
f=k=>k?[...k%3?[k]:[],...f(k-1)]:[] // 35 bytes

```

Try it online!

(this example code filters out values that are multiple of 3)

Notice that the spread operators is used twice (costing 6 bytes) and the payload value `k` has to be put within a singleton array (costing 2 more bytes).

An alternate approach is to apply `.flat()` immediately after each iteration, saving a byte:

```
f=k=>k?[k%3?k:[],f(k-1)].flat():[]  // 34 bytes

```

Try it online!

# Answer
> 6 votes
# Return intermediate result

You know that using the comma operator you can execute a sequence of expressions returning the last value. But abusing the literal array syntax, you can return any intermediate value. It's useful in .map() for instance.

```
// capitalize words
// f is a flag indicating if prev char is space
[...x].map(c=>(f?c=c.toUpperCase():0,f=c<'!',c),f=1).join('')

// shortened to ...
[...x].map(c=>[f?c.toUpperCase():c,f=c<'!'][0],f=1).join('')

```

# Answer
> 6 votes
## Primality-testing function

The following 28-byte function returns `true` for prime numbers and `false` for non-primes:

```
f=(n,x=n)=>n%--x?f(n,x):x==1

```

This can easily be modified to calculate other things. For example, this 39-byte function counts the number of primes less than or equal to a number:

```
f=(n,x=n)=>n?n%--x?f(n,x):!--x+f(n-1):0

```

If you already have a variable `n` that you want to check for primality, the primality function can be simplified quite a bit:

```
(f=x=>n%--x?f(x):x==1)(n)

```

### How it works

```
f = (         // Define a function f with these arguments:
  n,          //   n, the number to test;
  x = n       //   x, with a default value of n, the number to check for divisibility by.
) =>
  n % --x ?   //   If n is not divisible by x - 1,
  f(n, x)     //     return the result of f(n, x - 1).
              //   This loops down through all numbers between n and 0,
              //     stopping when it finds a number that divides n.
  : x == 1    //   Return x == 1; for primes only, 1 is the smallest number
              //     less than n that divides n.
              //   For 1, x == 0; for 0, x == -1.

```

Note: This will fail with a "too much recursion" error when called with a sufficiently large input, such as 12345. You can get around this with a loop:

```
f=n=>eval('for(x=n;n%--x;);x==1')

```

# Answer
> 5 votes
# Golfing Logical Operations in ES6

"GLOE (S6)"

## General Logic

Say you have constructed statements `s` and `t`. See if you can use any of the following replacements:

```
Traditional conjuction: s&&t
Equivalent conjuction: s*t OR s&t

Traditional disjunction: s||t
Equivalent disjunction: s+t OR s|t

```

(These may not work if the order is wrong; i.e. `+` and `*` have a lower order precedence than `||` and `&&` do.)

Also, here are some handy logical expressions:

* Either `s` or `t` is true/XOR: `s^t`
* `s` and `t` are the same truth value: `!s^t` or `s==t`

## Array logic

All members of `a` satisfy condition `p`:

```
a.every(p)                             // 10 bytes (11 bytes saved)
a.map(x=>c&=p(x),c=1)                  // 21 bytes (16 bytes saved)
for(i=0,c=1;i<a.length;c&=p(a[i++]));  // 37 bytes (hideously long)

```

At least one member of `a` satisfies condition `p`:

```
a.some(p)                            // 9  bytes (13 bytes saved)
a.map(x=>c|=p(x),c=0)                // 21 bytes (14 bytes saved)
for(i=c=0;i<a.length;c|=p(a[i++]));  // 35 bytes (just please no)

```

No members of `a` satisfy condition `p`: `!a.some(p)`.

Element `e` exists in array `a`:

```
a.includes(e)                        // 13 bytes, standard built-in
~a.indexOf(e)                        // 13 bytes, "traditional" method
a.find(x=>e==x)                      // 15 bytes, find (ES6)
a.some(x=>x==e)                      // 15 bytes, some (ES5)
(a+"").search(e)                     // 16 bytes, buggy
a.filter(t=>t==e).length             // 24 bytes, no reason to use this
for(i=c=0;i<a.length;c+=e==a[i++]);  // 35 bytes, super-traditional

```

Element `e` does *not* exist in array `a`:

```
!a.includes(e)
!~a.indexOf(e)
a.every(t=>t!=e)
!a.filter(t=>t==e).length
for(i=0,c=1;i<a.length;c*=e!=a[i++]);

```

# Answer
> 5 votes
# Yet another way to avoid `return`

You know you should use eval for arrow functions with multiple statements and a return. In some unusual case you can save more using an inner subfunction.

I say *unusual* because

1. The result returned must not be the last expression evalued in the loop
2. There must be (at least) 2 *different* initializations before the loop

In this case you can use an inner subfunction without return, having one of the initial values passed as a parameter.

**Example** Find the reciprocal of the sum of exp function for values in a range from a to b.

The long way - 55 bytes

```
(a,b)=>{for(r=0,i=a;i<=b;i++)r+=Math.exp(i);return 1/r}

```

With eval - 54 bytes

```
(a,b)=>eval("for(r=0,i=a;i<=b;i++)r+=Math.exp(i);1/r")

```

With an inner function - 53 bytes

```
(a,b)=>(i=>{for(r=0;i<=b;i++)r+=Math.exp(i)})(a)||1/r

```

Note that without the requirement of a lower range limit `a`, I can merge the initializations of i and r and the eval version is shorter.

# Answer
> 5 votes
## Using the currying syntax for dyadic and recursive functions

### Dyadic functions

Whenever a function takes exactly two arguments with no default values, using the currying syntax saves one byte.

**Before**

```
f =
(a,b)=>a+b  // 10 bytes

```

Called with `f(a,b)`

**After**

```
f =
a=>b=>a+b   // 9 bytes

```

Called with `f(a)(b)`

*Note*: This post in Meta confirms the validity of this syntax.

### Recursive functions

Using the currying syntax may also save some bytes when a recursive function takes several arguments but only needs to update some of them between each iteration.

**Example**

The following function computes the sum of all integers in the range `[a,b]`:

```
f=(a,b)=>a>b?0:b+f(a,b-1)   // 25 bytes

```

Because `a` remains unchanged during the whole process, we can save 3 bytes by using:

```
f =                         // no need to include this assignment in the answer anymore
a=>F=b=>a>b?0:b+F(b-1)      // 22 bytes

```

*Note*: As noticed by Neil in the comments, the fact that an argument is not explicitly passed to the recursive function does not mean that it should be considered immutable. If needed, we could modify `a` within the function code with `a++`, `a--` or whatever similar syntax.

# Answer
> 4 votes
# `Array#concat()` and the spread operator

This largely depends on the situation.

---

## Combining multiple arrays.

Prefer the concat function unless cloning.

**0 bytes saved**

```
a.concat(b)
[...a,...b]

```

**3 bytes wasted**

```
a.concat(b,c)
[...a,...b,...c]

```

**3 bytes saved**

```
a.concat()
[...a]

```

**6 bytes saved**

```
// Concatenate array of arrays
[].concat.apply([],l)
[].concat(...l)

```

---

## Prefer using an already existing array to `Array#concat()`.

Easy **4 bytes saved**

```
[].concat(a,b)
a.concat(b)

```

# Answer
> 4 votes
# Avoiding commas when storing lots of data

If you have a lot of data (i. e. indices, characters, …) that you need to store in an array, you might be better off leaving all commas away. This works best if every piece of data has the same string length, 1 obviously being optimal.

**43 Bytes (baseline)**

```
a=[[3,7,6,1,8,9,4,5,2],[5,4,3,2,7,6,5,4,3]]

```

**34 Bytes (no commas)**

```
a=[[..."376189452"],[..."543276543"]]

```

If you're willing to *change your array access*, you might reduce this even further, storing the same values like so:

**27 Bytes (same data, only changes array access)**

```
a=[..."376189452543276543"]

```

# Answer
> 4 votes
# Use `eval` instead of braces for arrow functions

Arrow functions are awesome. They take the form `x=>y`, where `x` is an argument and `y` is the return value. However, if you need to use a control structure, such as `while`, you would have to put braces, e.g. `=>{while(){};return}`. However, we can get around this; luckily, the `eval` function takes a string, evaluates that string as JS code, and *returns the last evaluated expression*. For example, compare these two:

```
x=>{while(foo){bar};return baz} // before
x=>eval('while(foo){bar};baz')  // after
//                            ^

```

We can use an extension of this concept to further shorten our code: in the eyes of `eval`, control structures also return their last evaluated expression. For example:

```
x=>{while(foo)bar++;return bar} // before
x=>eval('while(foo)++bar')      // after
//                        ^^^^^

```

# Answer
> 4 votes
# Destructuring assignments

ES6 introduces new syntax for destructuring assignments, i.e. cutting a value into pieces and assigning each piece to a different variable. Here are a few examples:

### Strings and arrays

```
a=s[0];b=s[1];       // 14 bytes
[a,b]=s;             //  8 bytes

a=s[0];s=s.slice(1); // 20 bytes
a=s.shift();         // 12 bytes, only works if s is an array
[a,...s]=s;          // 11 bytes, converts s to an array

```

### Objects

```
a=o.asdf;b=o.bye;c=o.length; // 28 bytes
{asdf:a,bye:b,length:c}=o;   // 26 bytes

a=o.a;b=o.b;c=o.c; // 18 bytes
{a,b,c}=o;         // 10 bytes

```

These assignments can also be used in function parameters:

```
f=a=>a[0]+a[1]+a[2]
f=([a,b,c])=>a+b+c

f=b=>b[1]?b[0]+f(b.slice(1)):b[0]*2
f=b=>b[1]?b.shift()+f(b):b[0]*2
f=([a,...b])=>b[0]?a+f(b):a*2

```

# Answer
> 4 votes
# Use `**` (ES7)

`**` is the new exponentiation operator. Occasionally useful.

```
Math.pow(2,2) // size: 13, result: 4
2**2          // size:  4, result: 4

```

# Answer
> 4 votes
# Convert BigInt back to Number (Chrome 67+ / Node.js 10.4+)

## !! ALERT : ESNext feature ahead !!

BigInt makes arbitrary-precision integer arithmetic more handy in JS, but there is a caveat - most already existing functions that accepts Number, does not accept BigInt. **UPDATE: array indexer DOES support BigInt for some reason.**

When we need to convert a BigInt back to Number for some reason, we cannot use `+n` (**this is explicitly forbidden in the specs**), but instead we need to use `Number(n)` -- except we do not really need to do so.

Instead of using `Number(n)`, we realise that we can actually convert the BigInt first into a String and then to a Number using `+`${n}`` , which saves 2 bytes.

But we can do better: wrap the BigInt with an array then directly cast it using `+` operator. This gives `+[n]` which saves 3 more bytes. Most importantly this **eliminates the use of `Number(n)` or even `(N=Number)(n)` and further `N(n)`s for multiple uses because `+[n]` has the same length as `N(n)`.**

You can test this out with this example:

```
s=163n;
console.log(Number(s)) // 9 bytes
console.log(+`${s}`)   // 7 bytes
console.log(+[s])      // 4 bytes

```

Try it online!

# Answer
> 4 votes
## Default parameters for variable initialization

Suppose you have some long duplicated subexpressions in a lambda:

```
d.map((x,i)=>[c[i]*c[i+1],c[i]*c[i+1]*x])

```

Unfortunately, you *cannot* just do `d.map((x,i)=>e=c[i]*c[i+1],[e,e*x])` because apparently `e` is not available in the scope of the second operand of the comma operator.

But you can "initialize" a variable in a default parameter declaration:

```
d.map((x,i,_,e=c[i]*c[i+1])=>[e,e*x])

```

You have to do it at an *unused* parameter position. Above, the function passed to `map` only ever gets invoked with three parameters and hence we can exploit the fourth parameter for our purposes.

# Answer
> 3 votes
# Set function parameter defaults

```
($,a,b,_)=>_!=undefined?'asdf':_ // before
($,a,b,_)=>_!=[]._?'asdf':_ // before, but a bit golfed
($,a,b,_='asdf')=>_ // after

```

This one's really useful...

However, be sure to understand that something like `_=>_||'asdf'` is shorter when you're only passing one (useful) argument to the function.

# Answer
> 3 votes
## Bind operator `::` (deprecated and unusable in more recent versions of JS)

The bind operator can be used to help shorten bytes over repeated functions:

```
(x='abc'.search(a))+x.search(b) // Before
(x=::'abc'.search)(a)+x(b)      // 5 bytes saved

```

Additionally if you want to use the function with a different `this` e.g.:

```
s[r='replace'](/a/g,'b')+s[r](/c/g,'d') // Before
(r=s.replace)(/a/g,'b')+s::r(/c/g,'d')  // 1 byte saved

```

# Answer
> 3 votes
# Splitting Strings

Surprised this hasn't been posted already (or maybe I missed it).

If you have an array of 5 or more strings, you can save bytes by instead `split`ting a string containing all the elements.

```
["one","two","three","four"]
"one,two,three,four".split`,` // 1 byte longer

```

```
["one","two","three","four","five"]
"one,two,three,four,five".split`,` // 1 byte shorter

```

```
["one","two","three","four","five","six"]
"one,two,three,four,five,six".split`,` // 3 bytes shorter

```

For each additional string in your array, you'll save a further 2 bytes with this approach.

If any of your strings contain a comma then change the delimiter to a differet character.

# Answer
> 3 votes
# Shortening Promise Chains with `async`/`await`

Taken from my answer here.

Sometimes you can shorten longer promise chains with `async`/`await`. The main benefit is from getting rid of the beginning of the arrow function in each `then` callback. `.then(x=>x` (10) gets replaced with `await(` (-4), but you first pay with `async` (+6). So to make up for the initial overhead of 6 bytes, you'd need at least two `then` chains to get any benefit.

```
+-------------+----------------+
| then chains | async overhead |
+-------------+----------------+
| 0           | +6             |
| 1           | +2             |
| 2           | -2             |
| 3           | -4             |
| …           | …              |
+-------------+----------------+

```

## Example 1

```
x=>x().then(y=>y.foo()).then(z=>z.bar())
async x=>await(await(x()).foo()).bar()

```

## Example 2

```
u=>fetch(u).then(r=>r.text()).then(t=>/\0/.test(t))
async u=>/\0/.test(await(await fetch(u)).text()))

```

# Answer
> 2 votes
## Shorten repeated function calls

If you have repeated calls to a function with a long-ish name, such as canvas manipulation:

```
c.lineTo(0,100);c.lineTo(100,100);c.lineTo(100,0);c.lineto(0,0);c.stroke()

```

The traditional way to shorten it would be to alias the function name:

```
c[l='lineTo'](0,100);c[l](100,100);c[l](100,0);c[l](0,0);c.stroke()

```

If you have enough calls, a better way is to create a function that does the job for you:

```
l=(x,y)=>c.lineTo(x,y);l(0,100);l(100,100);l(100,0);l(0,0);c.stroke()

```

If most of the function calls are chained, you can make the function return itself, allowing you to cut two bytes off of each successive call:

```
l=(x,y)=>c.lineTo(x,y)||l;l(0,100)(100,100)(100,0)(0,0);c.stroke()

```

Example usage: ,

# Answer
> 2 votes
# `Array.prototype.find` in array traversing

When traversing an array with `Array.prototype.map`, all elements are processed. However, when only the first truthy invocation is needed, flags are needed to stop subsequent elements from being processed. When processed with a recursion, more flags may be needed.

However, with `Array.prototype.find`, flags can be saved. `Array.prototype.find` receives a function with the same signature as `Array.prototype.map` does, and returns the first element that the function returns true for that element, or `undefined` if none returns true.

Consider an example of finding the first non-zero value from a numeric array:

```
// For-loop
A=>{for(i of A)if(i)return i}
// Array.prototype.map
A=>A.map(x=>i=i||x,i=0)&&i   // -3
// Array.prototype.filter
A=>A.filter(x=>x)[0]         // -9
// Array.prototype.find
A=>A.find(x=>x)              // -14

```

Real case - determine whether a numeric matrix has all non-zero values connected. The function is written in the way that can be invoked by both `map` and recursion:

```
// Uses map: 115 bytes
A=>w=>A.map(x=F=(u,i,a)=>u&&(x||!a)&&[-w,-1,1,w].map(v=>v*v>1|i%w+v>=0&i%w+v<w&&F(A[v+=i],v),x=A[i]=0))&&!+A.join``
// Uses find: 102 bytes
A=>w=>(A.find(F=(u,i)=>u&&[-w,-1,1,w].map(v=>v*v>1|i%w+v>=0&i%w+v<w&&F(A[v+=i],v),A[i]=0)),!+A.join``)

```

In the case above, we need to only rewrite one region, so we must use flags to avoid further invocation of `F` by `map`, but in the meantime we need to also let the recursion run, so another flag is used to indicate whether the invocation is by `map` or by recursion. With `find`, both flags are now unnecessary. However, be careful with the return value of the function. In this case, when `u` is zero then zero is returned, and otherwise an array is returned, which is truthy.

# Answer
> 1 votes
# Aliasing using `eval` and template strings

This one's more effective with longer code containing more repetition:

```
a.push([0,1,2,3,4,5,6,7,8,9,10].push([0,1,2,3,4,5,6,7,8,9,10].push([0,1,2,3,4,5,6,7,8,9,10]))) // before
a.push([...Array(11).keys()].push([...Array(11).keys()].push([...Array(11).keys()]))) // before - golfed
a.push((f=_=>[...Array(11).keys()])().push(f().push(f()))) // before - golfed more

eval(`a${b=`.push([...Array(11).keys()]`}${b+b})))`) // after

```

*Probably not the best example, but you get the idea.*

Although the use case is somewhat limited, it can save quite some bytes, especially because it can get at several char sequences (like `[function]([args])` or `[...`) that would otherwise be unable to be aliased.

Be careful with this, however; very often, using this technique can actually increase, not decrease, your byte count.

# Answer
> 1 votes
# (strawman) Use `do` expressions instead of `eval`ing strings

\[Babel preset\] and \[proposal\].

Comes with the added bonus of keeping syntax highlighting. This **might be a stretch** in some contests, but is nonetheless interesting. I think if it's supported in Babel, it should qualify as competing.

Consider the following function (37 bytes):

```
f=n=>{for(o=i=0;i<n;o+=++i);return o}

```

This might be golfed down with the classic `eval` trick (34 bytes (thank you everyone)):

```
f=n=>eval("for(o=i=0;i<n;)o+=++i")

```

But we can do better with `do` (30 bytes):

```
f=n=>do{for(o=i=0;i<n;)o+=++i}

```

Working example \- note that Babel needs `let` statements in all above functions as well.

Essentially what I'm trying to say is if a solution can be done with `eval`, you can almost always shave off a few bytes using `do`.

# Answer
> 1 votes
# Init with `fill` in `map` loop for range

Title may be hard to read.

Instead of

```
[...Array(n)].map((_,x)=>(y=0,...))

```

, write

```
Array(n).fill(0).map((y,x)=>...)

```

# Answer
> 1 votes
# Abuse BigInt comparison

Sometimes, you need to use BigInts to support arbitrary integers. These don't usually combine well with regular numbers, so you sometimes need to use BigInt literals like `5n`. But did you know that you can compare BigInts with regular numbers normally?

If you want to know whether a BigInt is e.g. greater than 100, you can use `n>100` instead of `n>100n`, for example.

An example of this is in this golf to this answer where comparison to 63 is used to save a byte.

# Answer
> 1 votes
# Shortening getting last element of `string`/`array`

Instead of

```
x[x.length-1] - 13 bytes
(l=x.length)...x[l-1] - (n + 18) bytes

```

use

```
x.at(-1) - 8 bytes
x.length...x.at(-1) - (n + 16) bytes

```

# Shortening getting last element of `array` with mutating

Instead of

```
x[x.length-1] - 13 bytes
x.at(-1) - 8 bytes

```

use

```
x.pop() - 7 bytes

```

---
Tags: code-golf, tips, javascript
---


title: Tips for golfing in Piet

text:
# Question
Title: Tips for golfing in Piet
Seeing that the current language for Learn You a Lang for Great Good is Piet, and that we don't seem to have a tips page for Piet yet, I decided to make one.

Piet is a stack-based esoteric programming language in which the programs are meant to resemble abstract drawings.

What are some general tips for golfing in Piet?

As usual, please keep the tips somewhat specific to Piet, and one tip per answer.

# Answer
> 10 votes
# Compact encoding and tools

**Use piet.bubbler.one for editing Piet!**

The default scoring method for code golf is in bytes. It gives Piet a significant disadvantage, since every Piet program must be a valid image file (which can be in PNG, GIF, or PPM format, but all of them costs well over 10 bytes per pixel). Also, TIO has `npiet` as the Piet interpreter (Try it online!), but it is unwieldy to use because it expects the hexdump of an image file.

In this regard, DLosc has made a tool called ascii-piet, which gives a printable-ASCII-based roughly-1-byte-per-pixel encoding for valid Piet programs.

The color table for ascii-piet looks like this:

|  | Red | Yellow | Green | Cyan | Blue | Magenta |
| --- | --- | --- | --- | --- | --- | --- |
| **Light** | t | v | r | s | q | u |
| **Medium** | l | n | j | k | i | m |
| **Dark** | d | f | b | c | a | e |
|  | **Black** | (space) | **White** | ? |  |  |

Using only these chars gives a plain 2D-lang-like scoring, where blanks at the end of each line can be omitted and a newline counts as 1 byte. In addition, you can change the last character of each line to uppercase (`_` for white) and omit all newlines.

As an example, the program

can be written like an ordinary 2D language as

```
ttttli
auqasj

```

which can be written in one line as

```
ttttlIauqasj

```

which has the score of 12 bytes = 12 codels.

Self-contained TIO setup: Try it online! (Protip: you can pass `-t` to npiet to get step-by-step information.)

If you use this setup and scoring, you should specify that ascii-piet is used for the encoding, like this:

```
# [Piet](https://github.com/cincodenada/bertnase_npiet) + [ascii-piet](https://github.com/dloscutoff/ascii-piet), 12 bytes

```

---

MasterPiets has a nice color chooser interface and a step-by-step debugger (click "Debugger" on the right side to open it). It has a few drawbacks though: you lose your work when you resize the grid, and some users have reported that Export to PNG doesn't work.

# Answer
> 6 votes
# Basic routing and halting

Routing and halting are two of the hardest walls when starting to write nontrivial Piet programs. The pointer moves in the unit of connected areas of the same color, and it chooses the next cell using the following variables:

* DP: Direction pointer. One of right, down, left, or up. Initially right.
* CC: Codel Chooser. One of left or right. Initially left.

Given the current area, DP, and CC, the next cell to move into is chosen as follows (hopefully more intuitive than the official doc):

* Imagine you are facing in the direction of DP.
* In the area you're stepping on, choose the cell(s) that are farthest from you.
* If there are multiple, choose the rightmost or leftmost cell out of them (in your view) based on CC.
* Walk to the chosen cell and move front once.

For example, if your current area looks like `x` in the following and DP=right and CC=left,

```
 h g
fxxxa
exx
  xxb
  cd

```

Then the next cell is `a`. The cells marked `a` to `h` are the cells you might enter next, depending on the current DP and CC.

If the next cell is black, or out of bounds, then the pointer tries the next combination of DP and CC - first swap CC, then rotate DP once clockwise, repeat. If all 8 combinations are tried and fails, it halts. (See the previous example again: the cells marked `a` to `h` are the cells that are tried in order.) Note that, by the spec, invalid commands (stack underflow and division by zero) are simply ignored and execution continues, so the *only* way to halt a program is via a trapped region.

So how to construct such a trapped region? The simplest ones I found are:

```
      x
...abcx
      x

```

and

```
...abcx
     xx

```

Can you see why each of these works? (It is impossible to trap in a 1-row program, or using areas of size 1 or 2.) And since these are the only trapping configuration of size 3, you will likely use one of these in every halting golfed program.

The turn-right-when-blocked behavior can be used to route in interesting ways. Some examples I found are:

```
# 2-row infinite loop
abc...xyz
zyx...abc

# 3-row finite loop with tail
# use conditional DP+ on `de` to turn right to move towards exit
# also can be used for a linear program; put `Push 1` on `cd` and `DP+` on `de`
abcabc z
exyzxayz
dcbacb z

# 2-row with small loops; use conditional DP+ on `de`
abcde...bcde...az
 pool   pool   zz

# more rows with few black cells to eventually lead to infinite loop
# note that seemingly unused cells can be used to push constants
>>>>>>>v
 ......v
>>>>v .v
^<<<<<<<

```

### A note on DP+ and CC+ commands (looping and if-else)

There is a command that can change the direction of movement (essentially DP). It is called "pointer" (at hue +3, darkness +1) in the official doc, but I like to call it `DP+`, as it directly adds the top value to the current DP (modulo 4). If you have a condition that evaluates to 0 or 1, you can use DP+ on that to turn right once based on a condition. This creates a branch in your program, and you can mainly use it to create a conditional loop. (If you somehow need to turn left instead, applying `*3` to the condition is the shortest method I can think of, which costs 4 more cells.)

There is CC+ ("switch" in official doc, hue +3, darkness +2) command too, which adds the top value to CC (modulo 2). This can be useful in creating if-else constructs: if you place CC+ at `ab` in the following code

```
...abcdexyz...
    buvwx

```

then the pointer follows the `cde` path or the `uvw` path based on the resulting CC. Then the `x` block acts as the merging point: since CC=right path is blocked, CC is toggled and the execution continues through `xyz...` with CC=left in both cases.

# Answer
> 2 votes
# If-else-bounce-merge

If you need to create control flow that splits and merges quickly, you might want to use this construction:

```
..xAbcd..Z
...Afgh..Zw

```

where `xA` is CC+ and `bcd..` and `fgh..` are two if-else paths. `w` must be surrounded by three blacks (or outside of the program). It is easiest to use when there's nothing to do for `bcd..`, in which case you can just fill that row with white codels. Otherwise, you need to check what `bcd..` does when run backwards.

An example where it prints 10 (newline) based on a condition.

The bounce part can be used without an if-else too, since it has an effect of fixing CC after it bounces back. primo's Hello World uses it for the 3-row layout to minimize wasted codels.

# Answer
> 2 votes
# Detecting if the stack is empty

If you ever run into a scenario where you need to check whether or not the stack is empty, you can simply run the following instructions:

```
dup, dup, minus, not

```

If the stack is empty, all these instructions will fall through and nothing will happen. But if the stack is non-empty, this code will essentially push a `1` on top of the pre-existing stack, without changing anything else.

You can then have a DP+ or CC+ instruction afterwards to branch your code based on whether or not the stack is empty. This can be particularly helpful in things like printing out the entire stack from the top to the bottom, where you can simply construct a loop with the check shown in this tip to exit the loop if the stack is empty.

Here's an example of that here. In this code, the stack is initialized as `6 5 4 3 5 2`. Then, it passes through the white codels (which are just there for clarity) and enter into the looping construct. Here, the check is ran (`dup, dup, minus, not`), with a `DP+` following it. If the stack is empty, then it simply passes through to the right and ends up in the halting construct (again, white codels added just for clarity). But if the stack is non-empty, there will be a `1` on the top of the stack, which will result in the DP pointing downwards after `DP+` is ran. The loop then continues with printing the value on the top of the stack, and then turning back up and to the right at the front of the loop to run the check again. This process is repeated until the stack is empty, which will then cause the IP to enter into the halting construct as stated previously. With the stack initialized as `6 5 4 3 5 2`, the code will result in `253456` being printed out (basically, the contents of the stack from the top to the bottom).

# Answer
> 2 votes
# A2-escape pattern

I wrote two answers today: factorial, number to binary.

Factorial:

Number to binary:

In both programs, `A1->A2` is a `DP+`. It is a no-op at start of a program (because the stack is empty), and is only meaningful after one iteration of the loop. When DP+ triggers, the IP escapes the loop through the 2nd column, which minimizes the wasted space on row C (in ascii-piet scoring). You can then do more stuff starting at C2 or D2 facing down.

This construct is useful when you can write the first part of the program in a single pure loop (no initialization before loop). The condition is easily met in Number to Binary because the only data needed is the input number, and it is OK to put `inN` in the loop (it is no-op when the input is exhausted).

It is a little harder in the case of Factorial, as you'd normally push 1 at the bottom which will be the "current product" in the loop. Fortunately with the current logic, the `DP+` is somewhat in the middle:

```
Initialize: 1 inN
Loop: dup 1 - 3 1 roll dup 1 > ! DP+ * 2 1 roll
                                 ^^^^^^^^^^^^^^

```

When the marked commands are put at the start of the program, `DP+ *` are no-ops, `2 1` push the two numbers, and `roll` is again a no-op (because there aren't two numbers to roll when 2 and 1 are removed). This leaves a 1 at the top of the stack (we can safely ignore the 2 below), which connects nicely to the logical start of the loop.

---
Tags: code-golf, tips
---


title: Staircase numbers

text:
# Question
Title: Staircase numbers
A staircase number is a positive integer **x** such that its **n**th digit (one indexed starting with the least significant digit) is equal to **x % (n + 1)**. Thats a bit of a mouthful so lets look at an example. Take **7211311**, if we take the modular residues of **7211311** on the range 2-8 we get the following:

```
7211311 % 2 = 1
7211311 % 3 = 1
7211311 % 4 = 3
7211311 % 5 = 1
7211311 % 6 = 1
7211311 % 7 = 2
7211311 % 8 = 7

```

These are the digits of **7211311**! Thus **7211311** is a staircase number.

## Task

Write code that takes when given a positive number as input, will output two distinct values one if the number *is* a staircase number and the other if it is not.

This is a competition so your aim should be to minimize the number of bytes in your source code.

## Test Cases

Here are the first 13 staircase numbers:

```
1, 10, 20, 1101, 1121, 11311, 31101, 40210, 340210, 4620020, 5431101, 7211311, 12040210

```

# Answer
# Haskell, 55 ~~57~~ bytes

```
f m|let n#x=n==0||n`mod`10==m`mod`x&&div n 10#(x+1)=m#2

```

A different approach than the other Haskell solution.

*Thanks xnor for saving 2 bytes.*
> 11 votes

# Answer
# Brachylog, ~~25~~ ~~21~~ ~~16~~ 14 bytes

```
{it+₂;?↔%}ᶠ↔c?

```

Try it online!

First Brachylog submission :D ~~probably very ungolfed~~...many thanks to Leaky Nun and Fatalize for encouragement and help to golf this from 25 all the way down to just 14. :) :)
> 9 votes

# Answer
# 05AB1E, 6 bytes

### Code:

```
ā>%JRQ

```

Uses the **05AB1E** encoding. Try it online!

### Explanation:

```
ā        # Get the range [1 .. len(input)]
 >       # Increment by 1
  %      # Vectorized modulo
   J     # Join the array into a single number
    RQ   # Reverse that number and check if it's equal to the original input

```
> 7 votes

# Answer
# Javascript, ~~42~~ ~~41~~ ~~39~~ 38 bytes

-4 bytes thanks to @Shaggy and @ETHProductions

```
s=>[...s].some(d=>s%i++^d,i=~s.length)

```

This takes the number as a string and returns `false` if the number is a staircase number and `true` otherwise.

Example code snippet:

```
f=
s=>[...s].some(d=>s%i++^d,i=~s.length)

function update() {
  o.innerText = f(document.getElementById("i").value)
}
```

```
<input id="i" type="number">
<button onclick="update()">Test</button>
<p id="o">
```
> 7 votes

# Answer
# Python 2, 54 bytes

```
f=lambda n,x=0:10**x>n or(`n%(x+2)`==`n`[~x])*f(n,x+1)

```

Try it online!
> 6 votes

# Answer
# Haskell, 60 bytes

Takes the number as an int

```
x n|s<-show n=reverse s==(rem n.(+1)<$>[1..length s]>>=show)

```
> 6 votes

# Answer
# Japt, ~~9~~ ~~7~~ 6 bytes

Takes input as a string.

```
Ô¶¡%´J

```

2 bytes saved with help from ETHproductions.

Try it

```
Ô¶¡%´J     :Implicit input of string U
Ô          :Reverse
 ¶         :Test for equality with
  ¡        :Map U
   %       :  Modulo
    ´J     :  J (initially -1) prefix decremented

```
> 5 votes

# Answer
# Mathematica, 60 bytes

```
FromDigits@Reverse@Mod[#,Range@Length@IntegerDigits@#+1]==#&

```

Try it online!

@alephalpha golfed it to 48

# Mathematica, 48 bytes

```
FromDigits@Reverse@Mod[#,Range[2,Log10@#+2]]==#&

```

next one is 24120020
> 5 votes

# Answer
# Neim, 6 bytes

Explanation:

```
         Get the length of the input, then create an exclusive range
 ᛖ        Add 2 to each element
         Modulus
          Reverse
          Join
         Check for equality

```

Try it online!
> 4 votes

# Answer
# Jelly, 7 bytes

```
DJ‘⁸%⁼Ṛ

```

Try it online!
> 3 votes

# Answer
# Pyth, 13 bytes

-1 bytes thanks to Okx.

```
qsjk_m%QhdSl`

```

Try it online!

**Explanation**

```
             QQ    # Implicit input
          Sl`Q     # Generate [1, len(str(Q))]
     m%Qhd         # For digit d in above range, perform Q % (d + 1)
 sjk_              # Reverse, then convert to number
q             Q    # Test equality with input

```

**Alternate solution**, still 13 bytes (thanks to karlkastor)

```
qi_.e%Q+2k`QT

```

Try it online! That's essentially the same as the first solution, excepted that it uses `i` to convert from array of numbers to a number, and that the range is generated differently.
> 2 votes

# Answer
# Python 2, 56 bytes

```
lambda x:all(`x%(i+2)`==`x`[~i]for i in range(len(`x`)))

```

Try it online!
> 2 votes

# Answer
# PHP, 43 bytes

```
for(;$r<$a=$argn;)$r=$a%~++$i.$r;echo$r>$a;

```

Try it online!

# PHP, 44 bytes

prints 1 for true and nothing for false

```
for(;$r<$a=$argn;)$r=$a%~++$i.$r;echo$r==$a;

```

Try it online!
> 2 votes

# Answer
# Perl 6, 32 bytes

```
{$_ eq[~] $_ «%«(1+.comb...2)}

```

Try it online!

* `.comb` is the number of characters in the string representation of the input argument `$_` (that is, the number of digits).
* `1 + .comb ... 2` is the sequence of numbers from one greater than the number of digits down to 2.
* `«%«` is the modulus hyperoperator that gives the remainder when `$_`, the input argument on its left, is divided by each of the elements of the sequence on its right: `$_ % 2, $_ % 3, ...`.
* `[~]` concatenates those digits into a new number, which is compared with the input argument using the string equality operator `eq`.
> 2 votes

# Answer
# C++,104 bytes

1) original version:

```
int main(){int N,T,R=1;cin>>N;T=N;for(int i=1;i<=log10(N)+1;i++){if(N%(i+1)!=T%10){R=0;}T/=10;}cout<<R;}

```

2) in a readable form:

```
int main()
{
    int N, T, R = 1;

    cin >> N;
    T = N;

    for (int i = 1; i <= log10(N) + 1; i++)
    {
        if (N % (i + 1) != T % 10)
        {
            R = 0;
        }

        T /= 10;
    }

    cout << R;
}

```

Try it Online!
> 2 votes

# Answer
# APL (Dyalog Extended), <sup>~~21~~</sup> 19 bytes

```
{⍵=10⊥⌽⍵|⍨1↓⍳1+≢⍕⍵}

```

Try it online!

Creates two lists of digits and check if they are equal.

## Explanation

```
{⍵=10⊥⌽⍵|⍨1↓⍳1+≢⍕⍵} ⍵ → input
               ≢⍕⍵  length of ⍵ as a string
             1+     +1
            ⍳       range from 1 to that
          1↓        Drop first element
       ⍵|⍨          ⍵ mod each element in range
      ⌽             reversed
   10⊥              converted from base 10
 ⍵=                 equals the input?

```
> 2 votes

# Answer
# Pari/GP, 42 bytes

```
n->Vecrev(s=digits(n))==[n%d|d<-[2..#s+1]]

```

Try it online!
> 1 votes

# Answer
# Python 2, ~~66 60 58~~ 57 bytes

* Thanks to @Leaky nun for 6 bytes: remove unneeded `x and` (shouldnot check for 0)
* Thanks to @Einkorn Enchanter for 1 byte: use of `enumerate`

```
lambda x:all(a==`x%(i+2)`for i,a in enumerate(`x`[::-1]))

```

Try it online!
> 1 votes

# Answer
# Charcoal, ~~20~~ 15 bytes

```
⌊Ｅθ⁼ιＩ﹪Ｉθ⁻⁺¹Ｌθκ

```

Try it online! Outputs `-` for a staircase number, nothing otherwise. Link is to verbose version of code.
> 1 votes

# Answer
## Java 8, 156 149 bytes

```
interface B{static void main(String[]s){String f="";for(int i=1;i<=s[0].length();)f=new Long(s[0])%++i+f;System.out.print(f.equals(s[0]));}}

```

Ungolfed :

```
interface B {
    static void main(String[] s) {
        String f = "";
        for (int i = 1; i <= s[0].length();)
            f = new Long(s[0]) % ++i + f;
        System.out.print(f.equals(s[0]));
    }
}

```

Try it Online !

**UPDATE :**
*-7 bytes* : removed useless `{}` and replaced `Integer.parseInt(...)` by `new Integer(...)`
*-9 bytes* : thanks to Kevin Cruijssen, removed a bunch of useless `()`, used `Long` instead of `Integer` and `print` instead of `println`. Thanks Kévin !
> 1 votes

# Answer
# Python 3: 63 Bytes

```
lambda m:all(int(x)==m%(n+2)for n,x in enumerate(str(m)[::-1]))

```

If I could count the number of times I wished 'enumerate' were shorter...

Try it online!
> 1 votes

# Answer
# Java (OpenJDK 8), 60 bytes

```
n->{int m=2,r=0,t=1;for(;n>=t;t*=10)r+=n%m++*t;return r==n;}

```

Try it online!

A non-string version.
> 1 votes

# Answer
# Haskell, 53 bytes

```
f n=foldr(\(k,_)a->10*a+mod n k)0(zip[2..]$show n)==n

```

Try it online!
> 1 votes

# Answer
## Python 2, 61 bytes

```
lambda x:[`x%(n+2)`for n in range(len(`x`))][::-1]==list(`x`)

```
> 0 votes

# Answer
# q/kdb+, 34 bytes

**Solution:**

```
{s~raze($)x mod'2+(|)(!)(#)s:($)x}

```

**Example:**

```
q){s~raze($)x mod'2+(|)(!)(#)s:($)x}7211311 / this is a staircase number (true)
1b
q){s~raze($)x mod'2+(|)(!)(#)s:($)x}7211312 / this is not (false)
0b
q)t(&){s~raze($)x mod'2+(|)(!)(#)s:($)x}each t:1 + til 1000000 / up to a million
1 10 20 1101 1121 11311 31101 40210 340210

```

**Explanation:**

Cast the input number to a string, count from 0..length of string, add 2 to all, reverse it and feed each number into `mod` along with the original input. Cast the result of the mod to a string and reduce the list, check if it is equal to the string of the input number:

```
{s~raze string x mod'2 + reverse til count s:string x} / ungolfed solution
{                                                    } / lambda function
                                           s:string x  / convert input to string, save as s
                                     count             / return length of this string
                                 til                   / like python's range() function
                         reverse                       / reverses the list
                     2 +                               / adds two to each element in the list
               x mod'                                  / ' is each both, so feeds x, and each element of the list to modulo function
        string                                         / converts output list to string list ("7";"2";"1"..etc)
   raze                                                / reduce list ("721...")
 s~                                                    / is s equal to this reduced list, returns boolean

```

**Notes:**

Most of the solution is for generating the `2,3,4..` list, I have another solution that does less stuff, but winds up being 37 bytes after golfing:

```
{s~x mod'reverse 2 + til count s:("J"$) each string x} / ungolfed
{s~x mod'(|)2+til(#)s:("J"$)each($)x}                  / golfed

```
> 0 votes

# Answer
## Clojure, 75 bytes

```
#(=(sort %)(sort(map(fn[i c](char(+(mod(Integer. %)(+ i 2))48)))(range)%)))

```

Input is a string, using `map` and the trailing `%` ended up being shorter than `for[i(range(count %))]` approach.
> 0 votes

# Answer
# Haskell, 62 bytes

`f x=and$zipWith(==)(reverse$show x)$map(head.show.mod x)[2..]`

Instead of reversing the (infinite) list of moduli, it truncates the list by zipping it with the reversed string-respresentation of the integral x, which it then ensures is equal element-wise.
> 0 votes

# Answer
# Perl 5, 41 bytes

39 bytes of code + 2 flags `-pa`

```
map{$\||=$_!=$F[0]%++$n}0,reverse/./g}{

```

Try it online!

Outputs nothing (undef) for staircase numbers, 1 for anything else
> 0 votes

# Answer
# MathGolf, 7 bytes

```
mækî)%Ñ

```

Input as a string.

Try it online.

**Explanation:**

```
m        # Map over each character of the (implicit) input-string,
 æ       # using the following four characters as inner code-block:
         #  (implicitly push the current character of the map)
  k      #  Push the input as an integer
   î     #  Push the 1-based map-index
    )    #  Increase it by 1
     %   #  Take the input-integer modulo (1-based) index+1
         # After the map, the digits are implicitly joined together to a string
      Ñ  # Check that this string is a palindrome
         # (after which the entire stack joined together is output implicitly as result)

```
> 0 votes

# Answer
# Arturo, 42 bytes

```
$[n][1every? reverse digits n'x->x=n%<=1+]

```

Try it
> 0 votes

# Answer
# Nibbles, 8.5 bytes

```
==.,,;`@~$%_+$~\@

```

Attempt This Online!

```
==.,,;`@~$%_+$~\@
==                Equal
  .                map
   ,                range
    ,                length
     ;                A :=
      `@~              decimal digits
         $              input
          %         mod
           _         input
            +        add
             $        it
              ~       1
               \   reverse
                @   A

```
> 0 votes

# Answer
# C (GCC), ~~65~~ 64 bytes

*-1 byte thanks to @ceilingcat*

```
i,j,k;f(n){for(i=j=k=1;++j,i<n;i*=10)k=n/i%10^n%j?0:k;return k;}

```

Try It Online!

Explanation:

```
i,j,k;
f(n)
{
    // i and k are 1, j is 2 since it's incremented before the first check for
    // i < n (and at the end of every loop). i is multiplied by 10 at the end
    // of each iteration.
    for(i=j=k=1;++j,i<n;i*=10)
        // If digit i doesn't equal n modulo j, set k to 0.
        k=n/i%10^n%j?
            0
        :
            k;

    return k;
}

```
> 0 votes

---
Tags: code-golf, number, decision-problem
---


title: Hilbert Primes Golf

text:
# Question
Title: Hilbert Primes Golf
Hilbert numbers are defined as positive integers of the form `4n + 1` for `n >= 0`. The first few Hilbert numbers are:

```
1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61, 65, 69, 73, 77, 81, 85, 89, 93, 97

```

The Hilbert number sequence is given by OEIS sequence A016813.

A related number sequence, the Hilbert primes, are defined as the Hilbert numbers `H > 1` that are not divisible by any Hilbert number `k` such that `1 < k < H`. The first few Hilbert primes are:

```
5, 9, 13, 17, 21, 29, 33, 37, 41, 49, 53, 57, 61, 69, 73, 77, 89, 93, 97, 101, 109, 113, 121, 129, 133, 137, 141, 149, 157, 161, 173, 177, 181, 193, 197

```

Naturally, OEIS has this sequence too.

Given a integer `n` such that `0 <= n <= 2^16` as input, output the `n`th Hilbert prime.

This is , so standard rules apply, and the shortest code in bytes wins.

# Leaderboard

The Stack Snippet at the bottom of this post generates the leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
## Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
## Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
## Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the snippet:

```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 65895; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 45941; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```

# Answer
# Pyth, 21 bytes

```
Lh*4bye.fqZf!%yZyT1hQ

```

Try it online: Demonstration or Test Suite

### Explanation:

```
Lh*4bye.fqZf!%yZyT1Q    implicit: Q = input number
L                       define a function y(b), which returns
 h*4b                      4*b + 1
                        this converts a index to its Hilbert number
       .f          hQ   find the first (Q+1) numbers Z >= 1, which satisfy:
           f      1        find the first number T >= 1, which satisfies:
            !%yZyT            y(Z) mod y(T) == 0
         qZ                test if the result is equal to Z

                        this gives a list of indices of the first Q Hilbert Primes
      e                 take the last index
     y                  apply y and print

```
> 3 votes

# Answer
## Haskell, 46 bytes

```
(foldr(\a b->a:[x|x<-b,mod x a>0])[][5,9..]!!)

```

An anonymous function.

The core is `foldr(\a b->a:[x|x<-b,mod x a>0])[][5,9..]`, which iterates through the arithmetic progression `5,9,13,...`, removing multiples of each one from the list to its right. This produces the infinite list of Hilbert primes. Then, `!!` takes the `n`th element.

I has tried making `(\a b->a:[x|x<-b,mod x a>0])` pointfree but didn't find a shorter way.
> 11 votes

# Answer
# CJam, ~~36~~ ~~33~~ ~~32~~ 23 bytes

```
5ri{_L+:L;{4+_Lf%0&}g}*

```

Try it online

The latest version is actually much more @MartinBüttner's than mine. The key idea in his suggested solution is to use two nested loops to find the n-th value that meets the condition. I thought I was being clever by using only a single loop in my original solution, but it turns out that the added logic cost more than I saved by not using a second loop.

Explanation

```
5       Push first Hilbert prime.
ri      Get input n and convert to integer.
{       Loop n times.
  _       Push a copy of current Hilbert prime.
  L       Push list of Hilbert primes found so far (L defaults to empty list).
  +       Prepend current Hilbert prime to list.
  :L      Store new list of Hilbert primes in variable L.
  ;       Pop list off stack.
  {       Start while loop for finding next Hilbert prime.
    4+      Add 4 to get next Hilbert number.
    _       Copy candidate Hilbert number.
    L       Push list of Hilbert primes found so far.
    f%      Element wise modulo of Hilbert number with smaller Hilbert primes.
    0&      Check for 0 in list of modulo values.
  }g      End while loop.
}*      End loop n times.

```
> 3 votes

# Answer
# Husk, 8 bytes

```
!ü¦¡+4 5

```

Try it online! Uses 1-based indexing.

## Explanation

```
!ü¦¡+4 5   Implicit input n.
   ¡       Iterate
    +4     addition of 4
       5   starting from 5: [5,9,13,17,..]
 ü         Uniquify by
  ¦        divisibility.
!          Get nth element.

```

Most of the work is done by `ü¦`. The function `ü`, when given a binary function `f` and a list, greedily constructs a subsequence where `f x y` is falsy for every (not necessarily adjacent) pair of elements `x, y`. In this case it picks a number if it's not divisible by any earlier pick. Then we just index into the resulting infinite list.
> 3 votes

# Answer
## Minkolang 0.14, ~~46~~ ~~37~~ 32 bytes

I didn't realize that the gosub was totally unnecessary... \>\_\>

```
n$z(xxi4*5+d(4-$d%)1=,z+$ziz-)N.

```

Try it here and check all test cases here.

### Explanation

```
n$z                                 Take number from input and store it in the register
   (                                Open while loop
    xx                              Dump the stack
      i4*5+                         Loop counter times 4 plus 5 (Hilbert number)
           d                        Duplicate
            (                       Open while loop
             4-                     Subtract 4
               $d                   Duplicate stack
                 %                  Modulo
                  )                 Exit while loop when top of stack is 0
                   1=,              0 if 1, 1 otherwise
                      z             Push register value
                       +            Add
                        $z          Pop and store in register
                          iz-       Subtract z from loop counter
                             )      Exit while loop when top of stack is 0
                              N.    Output as number and stop.

```

The register is used to store the target index. The outer while loop calculates each Hilbert number and does some bookkeeping. The inner while loop checks each Hilbert number for primality. If a Hilbert number is *not* a Hilbert prime, then the target is incremented so that the outer while loop has to repeat (at least) one more time, effectively skipping Hilbert composites.
> 2 votes

# Answer
## Mathematica, 65 bytes

```
Select[4Range[4^9]+1,Divisors[#][[2;;-2]]~Mod~4~FreeQ~1&][[#+1]]&

```

Generates the entire list and selects the element from it.
> 2 votes

# Answer
# Raku, 35 bytes

```
grep {$_%%none 5,9...^$_},(5,9...*)

```

Try it online!

This is an expression for the lazy, infinite list of Hilbert primes.

* `5, 9 ... *` is the infinite list of Hilbert numbers. (Raku infers that it's an arithmetic sequence from the first two elements.)
* `grep { $_ %% none 5, 9 ...^ $_ }` filters that list to those which are divisible (`%%`) by `none` of the Hilbert numbers up to, but not including (`...^`), the number being tested.
> 2 votes

# Answer
# Ruby, 60 bytes

```
h=->i{n=[];x=5;n.any?{|r|x%r<1}?x+=4: n<<x until e=n[i-1];e}

```

Only checks Hilbert prime factors.
> 1 votes

# Answer
# Matlab, 74 ~~83~~ bytes

```
function t=H(n)
x=5;t=x;while nnz(x)<n
t=t+4;x=[x t(1:+all(mod(t,x)))];end

```

Thanks to Tom Carpenter for removing 9 bytes!

Example use:

```
>> H(20)
ans =
   101

```
> 1 votes

# Answer
# Julia, 73 bytes

```
n->(a=[x=5];while length(a)<n;x+=4;all(k->mod(x,k)>0,a)&&push!(a,x)end;x)

```

Thanks Alex A. for saving 11 bytes! This uses the same algorithm as the Matlab and Ruby answers. Since Julia arrays are one-indexed, this starts with `f(1) == 5`.

My first attempt, using the Lazy package, is **106 bytes**. If you plan to run this in the REPL, make sure to add semicolons to the ends of the lines to suppress the infinite output. And call `Pkg.Add("Lazy")` if you don't already have it installed.

```
using Lazy
r=range
h=r(1,Inf,4)
p=@>>r() filter(n->n!=1&&all(map(x->mod(h[n],h[x])<1,2:n-1)))
f=n->h[p[n]]

```
> 1 votes

# Answer
# JavaScript (ES6), 73 bytes

```
n=>{for(i=0,t=2;i<=n;)i+=!/^(.(....)+)\1+$/.test(Array(t+=4));return t-1}

```

Just check Hilbert numbers one by one until we reach the nth Hilbert prime. Divisibility by Hilbert number is handled by regex.
> 1 votes

# Answer
# Jelly, ~~17~~ 15 bytes

```
ŻḤḤ‘ḍḍiɗċ1=2µ#Ṫ

```

Try it online!

Uses 1-indexing (e.g. `1 -> 5, 2 -> 9, etc.`), allowed by default on challenges.

## How it works

```
ŻḤḤ‘ḍḍiɗċ1=2µ#Ṫ - Main link. Takes n via STDIN
            µ#  - Execute the following on integers k = 1, 2, 3, ... until n integers return True:
Ż               -   Yield [0, 1, 2, ..., k]
 Ḥ              -   Unhalve; [0, 2, 4, ..., 2k]
  Ḥ             -   Unhalve; [0, 4, 8, ..., 4k]
   ‘            -   Increment; [1, 5, 9, ..., 4k+1]
       ɗ        -   Group the previous three links into a dyad.
                    Use l = [1, 5, ..., 4k+1] on the left and k on the right:
    ḍ           -     Each element in l is divisible by k?
      i         -     Index of k in l or 0?
     ḍ          -     1 or 0 is divisible by the index?
                    This yields a list with 2 1s for Hilbert primes
        ċ1      -   Count 1s
          =2    -   Equals 2?
              Ṫ - Take the last one i.e. the nth Hilbert prime

```
> 1 votes

# Answer
# Perl 5 `-p`, 56 bytes

```
$k=$.+=4;1while($k-=4)>1&&$.%$k;($k>1||--$_)&&redo;$_=$.

```

Try it online!
> 1 votes

# Answer
# JavaScript, ~~59~~ ~~58~~ 54 bytes

0-indexed and based on the (possibly erroneous?) observation that, just as all composite numbers are divisible by at least one prime, all *Hilbert* composites are also divisible by at least one Hilbert prime.

Here's a limited proof of that using the first 20000 Hilbert numbers.

We handle the edge case of `1` being neither prime nor composite below by hardcoding `5` as our stating point.

```
a=[x=5];f=n=>a[a.every(y=>x%y,x+=4)?a.push(x):n]||f(n)

```

Try it online!

## Explanation

We initialise an array `a=[5]`, which will hold the Hilbert primes, and an integer `x=5`, which we'll use as a temporary variable for the Hilbert numbers, outside the main function. Usually this wouldn't be possible because our rules require that everything be reusable by successive function calls, but here on each successive call of the function `a[n]` will either exist and be immediately returned or we'll resume building the array of primes from where we left off on the last call and continue until it does exist.

`f`, then, is our recursive function taking input via parameter `n`. On each iteration we increment `x` by `4` and then check that, for each existing prime `y` in `a`, `x%y>0`.

If it is then we `push` the new value of `x` to `a`, which returns the updated length of `a`. We use that to index into `a` but, as JavaScript uses 0-based indexing, `a[a.length]` will always return `undefined`, which is falsey, so we fall through the logical `OR` to execute a recursive call to `f(n)` and continue to do so until we encounter a Hilbert composite (i.e., for at least one `y` in `a`, `x%y===0`).

When we do encounter a composite we instead index `n` into `a` and, if it exists, return that value, or continue recursing until the next composite if it doesn't.
> 1 votes

# Answer
# Python, 80 bytes

```
f=lambda I,i=0,H=[2]:(i>I)*H[0]or f(I,i+all((p:=4*len(H)+1)%h for h in H),[p]+H)

```

Attempt This Online!

0-indexed (but it would be trivial to change to be 1-indexed). Stores the previous Hilbert numbers in `H`, and stores how many Hilbert primes have been found so far in `i`.
> 0 votes

---
Tags: code-golf, math, number, sequence, number-theory
---