fractional_indexer 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 9c3e15f1e2a102d07fb9fa39a650f28e959184a21bb347e8125df3c36437cfb5
4
- data.tar.gz: c83b4e10bcf12bed2604dcc2b230f481c0ad46ce7bd6f2777f3cb1fad3b836ad
3
+ metadata.gz: 865704ccf092a38ae85b07ddbc038a988c99a2f0914150bac94619e7c8112e43
4
+ data.tar.gz: a34702ada59473c1d9525fa003541ab91905ea187126c347d64acd33584e54e7
5
5
  SHA512:
6
- metadata.gz: ada9175bde75b29f21e7fe053cdcc0bb433c27c9fb9387de65d0b8816368f47a28108c410476b48f2bde9e5e4eb4855efe0aeef1fb0bce4291fd537a0403583b
7
- data.tar.gz: 82ee500b85f2dd7ad0883e3fbdf7028141e335e47010e47b9d305837dd45fd6c55d7f6d2e6f12ec8e83ad01cc4790a57238e4a37e82583ee1838c11cc86ef591
6
+ metadata.gz: 65aae946720a42593b27bc64107923436c646ec6be74799ee70e996f9b9e336dd0772d3457758c417d038f23037fff0e9bca7e71404f63d3251858c6595e4576
7
+ data.tar.gz: 866ddaeb65da5e6fbb0e0b5edd8859617e9e50720e6343e980d1898d093d6577c708efcec10ca805a90cd41312d48ec2c8bdecea84f2444a23653046fe9b7ceb
data/README.md CHANGED
@@ -3,16 +3,50 @@
3
3
  [![codecov](https://codecov.io/gh/kazu-2020/fractional_indexer/graph/badge.svg?token=OCCYE4EKT1)](https://codecov.io/gh/kazu-2020/fractional_indexer)
4
4
  [![test](https://github.com/kazu-2020/fractional_indexer/actions/workflows/ruby.yml/badge.svg?branch=main&event=push)](https://github.com/kazu-2020/fractional_indexer/actions/workflows/ruby.yml)
5
5
 
6
- > efficient data insertion and sorting through fractional indexing
6
+ > Efficient data insertion and sorting through fractional indexing
7
7
 
8
- This gem is designed to achieve "[Realtime editing of ordered sequences](https://www.figma.com/blog/realtime-editing-of-ordered-sequences/#fractional-indexing)" as featured in a Figma blog post.
8
+ ## Overview
9
9
 
10
- Specifically, it implements Fractional Indexing as a means of managing order, realized through strings. By managing indexes as strings, it significantly delays the occurrence of index duplication that can arise when implementing Fractional Indexing with floating-point numbers. Additionally, using strings allows for the representation of a much larger range of numbers in a single digit compared to decimal numbers (by default, a single digit is represented in base-62).
10
+ Fractional Indexer is a Ruby gem that implements **fractional indexing** for managing ordered sequences. Instead of using integer positions that require reindexing on insertion, it uses string-based keys that allow inserting items anywhere without affecting existing items.
11
11
 
12
- This gem was implemented based on the excellent article "[Implementing Fractional Indexing.](https://observablehq.com/@dgreensp/implementing-fractional-indexing)" I would like to express my gratitude to David Greenspan, the author of the article.
12
+ ### Why Fractional Indexing?
13
+
14
+ **Traditional integer indexing** requires shifting all subsequent items when inserting:
15
+
16
+ ```
17
+ Before: [A:1] [B:2] [C:3]
18
+ ↓
19
+ Insert X between A and B
20
+ ↓
21
+ After: [A:1] [X:2] [B:3] [C:4] ← B and C must be updated!
22
+ ```
23
+
24
+ **Fractional indexing** generates a key between existing keys without reindexing:
25
+
26
+ ```
27
+ Before: [A:"a0"] [B:"a1"] [C:"a2"]
28
+ ↓
29
+ Insert X between A and B
30
+ ↓
31
+ After: [A:"a0"] [X:"a0V"] [B:"a1"] [C:"a2"] ← No changes to B or C!
32
+ ```
33
+
34
+ ### Key Features
35
+
36
+ - **No reindexing required** - Insert items between any two existing items
37
+ - **String-based keys** - Avoids floating-point precision issues
38
+ - **Configurable base** - Supports base-10, base-62 (default), and base-94
39
+ - **Multiple key generation** - Generate multiple keys at once for batch operations
40
+
41
+ This gem implements the concepts from "[Realtime editing of ordered sequences](https://www.figma.com/blog/realtime-editing-of-ordered-sequences/#fractional-indexing)" (Figma Engineering Blog).
42
+
43
+ > [!TIP]
44
+ > **Using Rails?** Check out [narabikae](https://github.com/kazu-2020/narabikae) - an Active Record integration that makes fractional indexing as simple as `task.move_to_position_after(other_task)`
13
45
 
14
46
  ## Installation
15
47
 
48
+ Requires Ruby 3.3 or later.
49
+
16
50
  Add this line to your application's Gemfile:
17
51
 
18
52
  ```ruby
@@ -31,139 +65,300 @@ Or install it yourself as:
31
65
  gem install fractional_indexer
32
66
  ```
33
67
 
34
- ## Usage
68
+ ## Quick Start
69
+
70
+ ```ruby
71
+ require 'fractional_indexer'
72
+
73
+ # Step 1: Generate your first key
74
+ first_key = FractionalIndexer.generate_key
75
+ # => "a0"
76
+
77
+ # Step 2: Generate the next key (for appending)
78
+ second_key = FractionalIndexer.generate_key(prev_key: first_key)
79
+ # => "a1"
80
+
81
+ # Step 3: Insert between two keys
82
+ middle_key = FractionalIndexer.generate_key(prev_key: first_key, next_key: second_key)
83
+ # => "a0V"
35
84
 
36
- ### Generate Order key
85
+ # Result: first_key < middle_key < second_key
86
+ # "a0" < "a0V" < "a1"
87
+ ```
88
+
89
+ ## How It Works
90
+
91
+ ### Order Key Structure
92
+
93
+ An order key consists of two parts: an **integer part** and an optional **fractional part**.
94
+
95
+ ```
96
+ "a3012"
97
+ │└┬┘└┬┘
98
+ │ │ └── Fractional Part: "012" (optional, for fine-grained positioning)
99
+ │ └───── Integer Digits: "3" (the numeric value)
100
+ └─────── Prefix: "a" (indicates 1-digit positive integer)
101
+ ```
102
+
103
+ **Prefix rules:**
104
+ - `a` to `z`: Positive integers (a=1 digit, b=2 digits, ..., z=26 digits)
105
+ - `A` to `Z`: Negative integers (used for keys "before" zero)
106
+
107
+ **Examples:**
108
+
109
+ | Key | Integer Part | Fractional Part | Meaning |
110
+ |-----|-------------|-----------------|---------|
111
+ | `a5` | `a5` | (none) | Positive 1-digit: 5 |
112
+ | `b12` | `b12` | (none) | Positive 2-digit: 12 |
113
+ | `a3V` | `a3` | `V` | Between a3 and a4 |
114
+ | `Zz` | `Zz` | (none) | Largest negative number |
115
+
116
+ ### Key Generation Flow
37
117
 
38
- To generate an order key, use the `FractionalIndexer.generate_key` method.
39
- This method can take two arguments: prev_key and next_key, both of which can be either nil or a string (excluding empty strings).
118
+ The following diagram shows how `generate_key` determines which operation to perform:
40
119
 
41
- The characters that can be used in the strings are available for review in `FractionalIndexer.configuration.digits`.
120
+ ```mermaid
121
+ flowchart TD
122
+ A[generate_key] --> B{prev_key and next_key?}
123
+ B -->|Both nil| C["Return 'a0'<br/>(initial key)"]
124
+ B -->|Only prev_key| D["Increment<br/>(next key after prev)"]
125
+ B -->|Only next_key| E["Decrement<br/>(key before next)"]
126
+ B -->|Both provided| F["Midpoint<br/>(key between both)"]
127
+
128
+ D --> G["a0 → a1 → a2 → ..."]
129
+ E --> H["... → Zy → Zz → a0"]
130
+ F --> I["a0, a2 → a1<br/>a0, a1 → a0V"]
131
+ ```
132
+
133
+ ## Usage
134
+
135
+ ### Basic Usage
136
+
137
+ #### Generating a Single Key
42
138
 
43
139
  ```ruby
44
140
  require 'fractional_indexer'
45
141
 
46
- # create first order key
142
+ # Create the first order key (when no keys exist)
47
143
  FractionalIndexer.generate_key
48
144
  # => "a0"
49
145
 
50
- # increment
146
+ # Increment: generate key after a given key
51
147
  FractionalIndexer.generate_key(prev_key: 'a0')
52
148
  # => "a1"
53
149
 
54
- # decrement
150
+ # Decrement: generate key before a given key
55
151
  FractionalIndexer.generate_key(next_key: 'a0')
56
152
  # => "Zz"
57
153
 
58
- # between prev_key and next_key
154
+ # Between: generate key between two keys
59
155
  FractionalIndexer.generate_key(prev_key: 'a0', next_key: 'a2')
60
156
  # => "a1"
61
-
62
- # prev_key should be less than next_key
63
- FractionalIndexer.generate_key(prev_key: 'a2', next_key: 'a1')
64
- # => error
65
- FractionalIndexer.generate_key(prev_key: 'a1', next_key: 'a1')
66
- # => error
67
157
  ```
68
158
 
69
- ### Generate Multiple Order keys
70
-
71
- To generate multiple order keys, use the `FractionalIndexer.generate_keys` method.
159
+ #### Generating Multiple Keys
72
160
 
73
161
  ```ruby
74
- require 'fractional_indexer'
75
-
76
- # generate n order keys that sequentially follow a given prev_key.
162
+ # Generate 5 keys after "b11"
77
163
  FractionalIndexer.generate_keys(prev_key: "b11", count: 5)
78
164
  # => ["b12", "b13", "b14", "b15", "b16"]
79
165
 
80
- # generate n order keys that sequentially precede a given next_key.
166
+ # Generate 5 keys before "b11"
81
167
  FractionalIndexer.generate_keys(next_key: "b11", count: 5)
82
168
  # => ["b0w", "b0x", "b0y", "b0z", "b10"]
83
169
 
84
- # generate n order keys between the given prev_key and next_key.
170
+ # Generate 5 keys between "b10" and "b11"
85
171
  FractionalIndexer.generate_keys(prev_key: "b10", next_key: "b11", count: 5)
86
172
  # => ["b108", "b10G", "b10V", "b10d", "b10l"]
87
173
  ```
88
174
 
89
- ## Configure
175
+ #### Error Handling
176
+
177
+ ```ruby
178
+ # prev_key must be less than next_key
179
+ FractionalIndexer.generate_key(prev_key: 'a2', next_key: 'a1')
180
+ # => raises error
181
+
182
+ # prev_key and next_key cannot be equal
183
+ FractionalIndexer.generate_key(prev_key: 'a1', next_key: 'a1')
184
+ # => raises error
185
+ ```
186
+
187
+ ### Practical Examples
188
+
189
+ #### Example 1: Task List Management
190
+
191
+ ```ruby
192
+ # Managing a todo list with fractional indexing
193
+ tasks = []
194
+
195
+ # Add initial tasks
196
+ tasks << { id: 1, title: "Write code", position: FractionalIndexer.generate_key }
197
+ tasks << { id: 2, title: "Write tests", position: FractionalIndexer.generate_key(prev_key: tasks.last[:position]) }
198
+ tasks << { id: 3, title: "Deploy", position: FractionalIndexer.generate_key(prev_key: tasks.last[:position]) }
199
+
200
+ tasks.each { |t| puts "#{t[:position]}: #{t[:title]}" }
201
+ # a0: Write code
202
+ # a1: Write tests
203
+ # a2: Deploy
204
+
205
+ # Insert "Code review" between "Write tests" and "Deploy"
206
+ new_position = FractionalIndexer.generate_key(
207
+ prev_key: tasks[1][:position], # "a1"
208
+ next_key: tasks[2][:position] # "a2"
209
+ )
210
+ tasks << { id: 4, title: "Code review", position: new_position }
211
+
212
+ # Sort by position
213
+ tasks.sort_by! { |t| t[:position] }
214
+ tasks.each { |t| puts "#{t[:position]}: #{t[:title]}" }
215
+ # a0: Write code
216
+ # a1: Write tests
217
+ # a1V: Code review ← Inserted without changing other positions!
218
+ # a2: Deploy
219
+ ```
220
+
221
+ #### Example 2: Prepending and Appending
222
+
223
+ ```ruby
224
+ # Start with a middle item
225
+ items = [{ name: "B", pos: FractionalIndexer.generate_key }]
226
+ # items[0][:pos] => "a0"
227
+
228
+ # Append to the end (only prev_key)
229
+ items << { name: "C", pos: FractionalIndexer.generate_key(prev_key: items.last[:pos]) }
230
+ # items[1][:pos] => "a1"
231
+
232
+ # Prepend to the beginning (only next_key)
233
+ items.unshift({ name: "A", pos: FractionalIndexer.generate_key(next_key: items.first[:pos]) })
234
+ # items[0][:pos] => "Zz"
235
+
236
+ items.sort_by { |i| i[:pos] }.each { |i| puts "#{i[:pos]}: #{i[:name]}" }
237
+ # Zz: A
238
+ # a0: B
239
+ # a1: C
240
+ ```
241
+
242
+ #### Example 3: Batch Insertion
243
+
244
+ ```ruby
245
+ # Insert 5 items between two existing items at once
246
+ existing = [
247
+ { name: "First", pos: "a0" },
248
+ { name: "Last", pos: "a1" }
249
+ ]
250
+
251
+ # Generate 5 keys between "a0" and "a1"
252
+ new_positions = FractionalIndexer.generate_keys(
253
+ prev_key: existing[0][:pos],
254
+ next_key: existing[1][:pos],
255
+ count: 5
256
+ )
257
+ # => ["a08", "a0G", "a0V", "a0d", "a0l"]
258
+
259
+ new_items = new_positions.map.with_index do |pos, i|
260
+ { name: "Item #{i + 1}", pos: pos }
261
+ end
262
+
263
+ all_items = (existing + new_items).sort_by { |i| i[:pos] }
264
+ all_items.each { |i| puts "#{i[:pos]}: #{i[:name]}" }
265
+ # a0: First
266
+ # a08: Item 1
267
+ # a0G: Item 2
268
+ # a0V: Item 3
269
+ # a0d: Item 4
270
+ # a0l: Item 5
271
+ # a1: Last
272
+ ```
273
+
274
+ #### Example 4: Key Growth Over Time
275
+
276
+ When repeatedly inserting at the same position, keys grow longer to maintain precision:
277
+
278
+ ```ruby
279
+ # Repeatedly insert at the beginning
280
+ key = FractionalIndexer.generate_key # => "a0"
281
+ puts "Initial: #{key}"
90
282
 
91
- ### base
283
+ 5.times do |i|
284
+ key = FractionalIndexer.generate_key(prev_key: key, next_key: "a1")
285
+ puts "Insert #{i + 1}: #{key}"
286
+ end
92
287
 
93
- You can set the base (number system) used to represent each digit.
94
- The possible values are :base_10, :base_62, and :base_94. (The default is :base_62)
288
+ # Initial: a0
289
+ # Insert 1: a0V
290
+ # Insert 2: a0l
291
+ # Insert 3: a0t
292
+ # Insert 4: a0x
293
+ # Insert 5: a0z
294
+ ```
95
295
 
96
- Note: base_10 is primarily intended for operational verification and debugging purposes.
296
+ ## Configuration
297
+
298
+ ### Base System
299
+
300
+ You can configure the base (number system) used to represent each digit. The possible values are `:base_10`, `:base_62` (default), and `:base_94`.
301
+
302
+ | Base | Characters | Use Case |
303
+ |------|-----------|----------|
304
+ | `:base_10` | `0-9` | Debugging, human-readable |
305
+ | `:base_62` | `0-9`, `A-Z`, `a-z` | General use (default) |
306
+ | `:base_94` | All printable ASCII | Maximum density |
97
307
 
98
308
  ```ruby
99
309
  require 'fractional_indexer'
100
310
 
311
+ # Base 10 (for debugging)
101
312
  FractionalIndexer.configure do |config|
102
313
  config.base = :base_10
103
314
  end
104
315
  FractionalIndexer.configuration.digits.join
105
316
  # => "0123456789"
106
317
 
318
+ # Base 62 (default)
107
319
  FractionalIndexer.configure do |config|
108
320
  config.base = :base_62
109
321
  end
110
322
  FractionalIndexer.configuration.digits.join
111
323
  # => "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
112
324
 
325
+ # Base 94 (maximum density)
113
326
  FractionalIndexer.configure do |config|
114
327
  config.base = :base_94
115
328
  end
116
329
  FractionalIndexer.configuration.digits.join
117
- # => "!\"\#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
330
+ # => "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
118
331
  ```
119
332
 
120
- ## Order key
121
-
122
- This section explains the structure of the string that represents an Order Key.
123
- An Order Key string is broadly divided into two parts: the integer part and the fractional part.
124
-
125
- Note: For ease of understanding, the explanation from here on will be based on the decimal system ('0' ~ '9')
333
+ ## Related Projects
126
334
 
127
- ### Integer Part
335
+ ### narabikae
128
336
 
129
- The integer part of the Order Key begins with a `mandatory prefix` that indicates the number of digits. This prefix is represented by one of the letters A to Z or a to z.
130
- a is 1 digit, b is 2 digits, c is 3 digits ...... and z represents 26 digits.
131
- The number of characters following the prefix must match the number of digits indicated by the prefix.
132
- For example, if the prefix is a, a valid key could be 'a8', and if the prefix is c, a valid key could be 'c135'.
337
+ If you're using **Ruby on Rails** with **Active Record**, check out [narabikae](https://github.com/kazu-2020/narabikae) - a gem that integrates Fractional Indexer directly into your models for seamless ordering.
133
338
 
134
339
  ```ruby
135
- 'a9' # Valid
136
- 'b10' # Valid
137
- 'b9' # Invalid (The prefix 'b' requires two digits)
138
- 'c123' # Valid
139
- 'c12' # Invalid (The prefix 'c' requires three digits)
140
- ```
141
-
142
- Additionally, leveraging the characteristic that uppercase letters have a lower ASCII value than lowercase letters, a to z represent positive integers, while A to Z represent negative integers.
340
+ class Task < ApplicationRecord
341
+ narabikae :position, size: 200
342
+ end
143
343
 
144
- ### Fractional Part
344
+ # Move a task after another
345
+ task.move_to_position_after(other_task)
145
346
 
146
- The Fractional Part refers to the portion of the string that follows the Integer Part, excluding the Integer Part itself.
347
+ # Move a task before another
348
+ task.move_to_position_before(other_task)
147
349
 
148
- ```ruby
149
- 'a3012'
150
- # 'a3' : Integer Part
151
- # '012': Fractional Part
350
+ # Move a task between two others
351
+ task.move_to_position_between(task_a, task_b)
152
352
  ```
153
353
 
154
- The Fractional Part cannot end with the first character of the base being used (e.g., '0' in base_10). This rule mirrors the mathematical principle that, for example, 0.3 and 0.30 represent the same value.
155
-
156
- ```ruby
157
- 'a32' # Valid
158
- 'a320' # Invalid (The Fractional Part cannot end with '0' in base_10)
159
- ```
160
-
161
- This section clarifies the concept and rules regarding the Fractional Part of an Order Key, with examples to illustrate what constitutes a valid or invalid Fractional Part.
162
-
163
354
  ## Contributing
164
355
 
165
- Bug reports and pull requests are welcome on GitHub at <https://github.com/kazu-2020/fractional_indexer>.
356
+ Bug reports and pull requests are welcome on GitHub at <https://github.com/kazu-2020/fractional_indexer>. See [CONTRIBUTING.md](CONTRIBUTING.md) for pull request labels and the release process.
166
357
 
167
358
  ## License
168
359
 
169
360
  The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
361
+
362
+ ## Acknowledgments
363
+
364
+ This gem was implemented based on the excellent article "[Implementing Fractional Indexing](https://observablehq.com/@dgreensp/implementing-fractional-indexing)" by David Greenspan. Thank you for the clear explanation and reference implementation!
@@ -3,8 +3,8 @@
3
3
  module FractionalIndexer
4
4
  class OrderKey
5
5
  INTEGER_BASE_DIGIT = 2
6
- POSITIVE_SIGNS = ("a".."z").freeze
7
- NEGATIVE_SIGNS = ("A".."Z").freeze
6
+ POSITIVE_SIGNS = ("a".."z")
7
+ NEGATIVE_SIGNS = ("A".."Z")
8
8
 
9
9
  attr_reader :key
10
10
 
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module FractionalIndexer
4
- VERSION = "0.4.0"
4
+ VERSION = "0.5.0"
5
5
  end
metadata CHANGED
@@ -1,20 +1,20 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: fractional_indexer
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.4.0
4
+ version: 0.5.0
5
5
  platform: ruby
6
6
  authors:
7
- - kazu
7
+ - matazou
8
8
  autorequire:
9
- bindir: exe
9
+ bindir: bin
10
10
  cert_chain: []
11
- date: 2024-03-10 00:00:00.000000000 Z
11
+ date: 2026-10-14 00:00:00.000000000 Z
12
12
  dependencies: []
13
13
  description: |
14
14
  FractionalIndexer is a Ruby gem designed to leverage fractional indexing for ordering within lists or data structures.
15
15
  it enables efficient sorting and insertion of large volumes of data.
16
16
  email:
17
- - matazou@gmail.com
17
+ - 64774307+kazu-2020@users.noreply.github.com
18
18
  executables: []
19
19
  extensions: []
20
20
  extra_rdoc_files: []
@@ -32,8 +32,12 @@ homepage: https://github.com/kazu-2020/fractional_indexer
32
32
  licenses:
33
33
  - MIT
34
34
  metadata:
35
+ homepage_uri: https://github.com/kazu-2020/fractional_indexer
36
+ changelog_uri: https://github.com/kazu-2020/fractional_indexer/releases
37
+ bug_tracker_uri: https://github.com/kazu-2020/fractional_indexer/issues
35
38
  source_code_uri: https://github.com/kazu-2020/fractional_indexer
36
- changelog_uri: https://github.com/kazu-2020/fractional_indexer
39
+ allowed_push_host: https://rubygems.org/
40
+ rubygems_mfa_required: 'true'
37
41
  post_install_message:
38
42
  rdoc_options: []
39
43
  require_paths:
@@ -42,14 +46,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
42
46
  requirements:
43
47
  - - ">="
44
48
  - !ruby/object:Gem::Version
45
- version: '0'
49
+ version: '3.3'
46
50
  required_rubygems_version: !ruby/object:Gem::Requirement
47
51
  requirements:
48
52
  - - ">="
49
53
  - !ruby/object:Gem::Version
50
54
  version: '0'
51
55
  requirements: []
52
- rubygems_version: 3.4.10
56
+ rubygems_version: 3.5.22
53
57
  signing_key:
54
58
  specification_version: 4
55
59
  summary: efficient data insertion and sorting through fractional indexing