├── .gitattributes ├── .github └── workflows │ └── build.yml ├── .gitignore ├── .npmrc ├── LICENSE ├── README.md ├── index.html ├── package.json └── spec.emu /.gitattributes: -------------------------------------------------------------------------------- 1 | index.html -diff merge=ours 2 | spec.js -diff merge=ours 3 | spec.css -diff merge=ours 4 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Deploy spec 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | 9 | steps: 10 | - uses: actions/checkout@v2 11 | - uses: actions/setup-node@v1 12 | with: 13 | node-version: '12.x' 14 | - run: npm install 15 | - run: npm run build 16 | - name: commit changes 17 | uses: elstudio/actions-js-build/commit@v3 18 | with: 19 | commitMessage: "fixup: [spec] `npm run build`" 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Runtime data 7 | pids 8 | *.pid 9 | *.seed 10 | 11 | # Directory for instrumented libs generated by jscoverage/JSCover 12 | lib-cov 13 | 14 | # Coverage directory used by tools like istanbul 15 | coverage 16 | 17 | # nyc test coverage 18 | .nyc_output 19 | 20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 21 | .grunt 22 | 23 | # node-waf configuration 24 | .lock-wscript 25 | 26 | # Compiled binary addons (http://nodejs.org/api/addons.html) 27 | build/Release 28 | 29 | # Dependency directories 30 | node_modules 31 | jspm_packages 32 | 33 | # Optional npm cache directory 34 | .npm 35 | 36 | # Optional REPL history 37 | .node_repl_history 38 | 39 | # Only apps should have lockfiles 40 | yarn.lock 41 | package-lock.json 42 | npm-shrinkwrap.json 43 | pnpm-lock.yaml 44 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 ECMA TC39 and contributors 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Proposal for `a[^i]` syntax 2 | 3 | A JavaScript proposal to add `a[^i]` syntax for `a[a.length - i]` 4 | 5 | Stage: 0 6 | 7 | Champions: HE Shi-Jun (hax) 8 | 9 | ## Rationale 10 | 11 | For many years, programmers have asked for the ability to do "negative indexing" of JS Arrays, like you can do with Python. That is, asking for the ability to write `arr[-1]` instead of `arr[arr.length-1]`, where negative numbers count backwards from the last element. 12 | 13 | Unfortunately, JS's language design makes this impossible. The `[]` syntax is not specific to Arrays and Strings; it applies to all objects. Referring to a value by index, like `arr[1]`, actually just refers to the property of the object with the key "1", which is something that any object can have. So `arr[-1]` already "works" in today's code, but it returns the value of the "-1" property of the object, rather than returning an index counting back from the end. 14 | 15 | This proposal suggests adding a `arr[^N]` syntax (follow the prior art of C#), which just work as `arr[arr.length - N]`, with the semantics as described above. 16 | 17 | ## Examples 18 | 19 | ```js 20 | let a = [1, 2, 3, 4] 21 | a[^1] // 4 22 | ++a[^1] // 5 23 | a[^0] // a[4], undefined 24 | a[^0] = 10 25 | a // [1, 2, 3, 5, 10] 26 | ``` 27 | 28 | ## Semantics 29 | 30 | `a[^i]` work as `a[CalcIndexFromEnd(a, i)]`. 31 | 32 | ```js 33 | function CalcIndexFromEnd(a, i) { 34 | // TBD: how to handle non-index cases? [1] 35 | return LengthOfArrayLike(a) - Number(i) 36 | } 37 | ``` 38 | [1] See [#5](https://github.com/hax/proposal-index-from-end/issues/5) 39 | 40 | Note, `a[^i]` will have two Get operations on `a` which the first is accessing `a.length`. And `a[^i] += 1` only access `a.length` once. 41 | 42 | ## Transpiling 43 | 44 | ```js 45 | // x = EXPR[^N] 46 | // -> 47 | x = ((a, n) => a[CalcIndexFromEnd(a, n)])(EXPR, N) 48 | ``` 49 | 50 | ```js 51 | // EXPR[^N] = VALUE 52 | // -> 53 | ((a, n, v) => (a[CalcIndexFromEnd(a, n)] = v))(EXPR, N, VALUE) 54 | ``` 55 | 56 | ## Comparison of `arr[^N]` to `arr[arr.length - N]` 57 | 58 | Currently, to access a value from the end of an indexable object, the common practice is to write `arr[arr.length - N]`, where N is the Nth item from the end. This requires naming the indexable twice, additionally adds 7 more characters for the `.length`, and is hostile to anonymous values; you can't use this technique to grab the last item of the return value of a function unless you first store it in a temp variable. 59 | 60 | ## Comparison of `arr[^N]` to `arr.at(-N)` 61 | 62 | ### Generality 63 | 64 | `arr[^N]` work for both read and write. 65 | 66 | `.at()` only applies to read. 67 | 68 | `arr[^N]` work for everything which is Array Like. 69 | 70 | `.at()` only applies to Array, TypedArray, String. 71 | 72 | ### Ergonomics 73 | 74 | Similar, though `arr[^N]` is 3 chars shorter than `arr.at(-N)` 75 | 76 | ### Learning, understanding and memory cost 77 | 78 | `arr[^N]` could be think as pure syntax sugar, so every JS programmers could learn it in 1 minute. 79 | 80 | `.at()` looks also easy, but in real programming there are much things to consider, need to RTFM: 81 | - Which objects have the `at()` method? Does strings have it? Does DOM collections have it? 82 | - Does `.at()` throw or return `undefined` for out of range index? 83 | - Is `string.at()` codepoint safe? 84 | - What `.at(-0)` means? 85 | - etc. 86 | 87 | ### Adoption cost 88 | 89 | Similar, `arr[^N]` need transpiling but no runtime polyfill; `.at()` need no transpiling but runtime polyfill. 90 | 91 | ### Relation to other proposals 92 | 93 | `arr[^N]` could be extended to slice notation: `arr[0:^N]` (drop last N items), `arr[^N:^0]` (take last N items), which solve the block issue (syntax/semantic inconsitency of `a[-1]` with `a[0:-1]`) of slice notation. 94 | 95 | ### Edge case 96 | 97 | Note, `^N` always means `arr.length - N`, so if `N` is 0, it means `arr.length`, as programmer expect. On the other side, `a.at(-N)` and `a.slice(-N)` have the edge case of `-0` which behave same as `0`, it's very likely not programmers expect and error-prone. This edge case is very common in `slice` usage, but may also affect `at`, for example code `if (arr.at(-N) !== undefined) ...`. 98 | 99 | See the discussions of `-0` edge case in various places: 100 | 101 | - https://github.com/rust-lang/rfcs/issues/2249#issuecomment-352128826 102 | - https://stackoverflow.com/questions/39460528/in-string-prototype-slice-should-slice0-0-and-slice0-0-output-the-sam/39461147 103 | - https://stackoverflow.com/questions/31740252/when-use-negative-number-to-slice-a-string-in-python-0-is-disabled?noredirect=1&lq=1 104 | - https://bytes.com/topic/python/answers/504522-string-negative-indices 105 | - https://tesarek.me/articles/slicing-primer#indexing 106 | - https://open.cs.uwaterloo.ca/python-from-scratch/2/9/transcript 107 | - https://news.ycombinator.com/item?id=13186225 108 | 109 | 110 | ## FAQ 111 | 112 | ### Why `^i` syntax is not 0-based but 1-based? 113 | 114 | To get the last element, you should use `a[^1]`. But it's still 0-based, and `^0` means the end position of the indexed collection (aka. the value of the `length` property). This make `a[^i]` be a better version of `a.at(-i)` or `a[a.length - i]`, and fit for slice notation proposal. See [the discussion](https://github.com/hax/proposal-index-from-end/issues/3#issuecomment-766686344) for more information. 115 | 116 | ## Prior arts 117 | 118 | ### C# 8 `^fromEnd` (*index from end* operator) 119 | - https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/ranges#systemindex 120 | - https://stackoverflow.com/questions/54092458/why-doesnt-the-new-hat-operator-index-from-the-c-sharp-8-array-slicing-feature/54092520 121 | - https://www.reddit.com/r/csharp/comments/arknnk/c_8_introducing_index_struct_and_a_brand_new/ 122 | 123 | ### D `a[$-1]` 124 | 125 | - https://dlang.org/spec/arrays.html#array-length 126 | - https://dlang.org/spec/operatoroverloading.html#dollar 127 | 128 | ### Raku (formerly Perl 6) drop Perl's `@a[-i]` and introduce `@a[*-i]` 129 | - https://docs.raku.org/language/traps#Referencing_the_last_element_of_an_array 130 | - https://docs.raku.org/language/subscripts#From_the_end 131 | - https://design.raku.org/S09.html#Negative_and_differential_subscripts 132 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Proposal Title Goes Here

Stage -1 Draft / November 16, 2023

Proposal Title Goes Here

1855 | 1856 | 1857 |

1 This is an emu-clause

1858 |

This is an algorithm:

1859 |
  1. Let proposal be undefined.
  2. If IsAccepted(proposal),
    1. Let stage be 0.
  3. Else,
    1. Let stage be -1.
  4. Return ? ToString(proposal).
1860 |
1861 |

A Copyright & Software License

1862 | 1863 |

Copyright Notice

1864 |

© 2023 Your Name(s) Here

1865 | 1866 |

Software License

1867 |

All Software contained in this document ("Software") is protected by copyright and is being made available under the "BSD License", included below. This Software may be subject to third party rights (rights from parties other than Ecma International), including patent rights, and no licenses under such third party rights are granted under this license even if the third party concerned is a member of Ecma International. SEE THE ECMA CODE OF CONDUCT IN PATENT MATTERS AVAILABLE AT https://ecma-international.org/memento/codeofconduct.htm FOR INFORMATION REGARDING THE LICENSING OF PATENT CLAIMS THAT ARE REQUIRED TO IMPLEMENT ECMA INTERNATIONAL STANDARDS.

1868 | 1869 |

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1870 | 1871 |
    1872 |
  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  2. 1873 |
  3. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  4. 1874 |
  5. Neither the name of the authors nor Ecma International may be used to endorse or promote products derived from this software without specific prior written permission.
  6. 1875 |
1876 | 1877 |

THIS SOFTWARE IS PROVIDED BY THE ECMA INTERNATIONAL "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ECMA INTERNATIONAL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

1878 | 1879 |
1880 |
-------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "name": "template-for-proposals", 4 | "description": "A repository template for ECMAScript proposals.", 5 | "scripts": { 6 | "start": "npm run build-loose -- --watch", 7 | "build": "npm run build-loose -- --strict", 8 | "build-loose": "ecmarkup --verbose spec.emu index.html" 9 | }, 10 | "homepage": "https://github.com/tc39/template-for-proposals#readme", 11 | "repository": { 12 | "type": "git", 13 | "url": "git+https://github.com/tc39/template-for-proposals.git" 14 | }, 15 | "license": "MIT", 16 | "devDependencies": { 17 | "ecmarkup": "^4.0.0" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /spec.emu: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
 7 | title: Proposal Title Goes Here
 8 | stage: -1
 9 | contributors: Your Name(s) Here
10 | 
11 | 12 | 13 |

This is an emu-clause

14 |

This is an algorithm:

15 | 16 | 1. Let _proposal_ be *undefined*. 17 | 1. If IsAccepted(_proposal_), 18 | 1. Let _stage_ be *0*. 19 | 1. Else, 20 | 1. Let _stage_ be *-1*. 21 | 1. Return ? ToString(_proposal_). 22 | 23 |
24 | --------------------------------------------------------------------------------