瀏覽代碼

Added ValueBox/Cell to mol-util

David Sehnal 7 年之前
父節點
當前提交
dbb9d5a35e
共有 2 個文件被更改,包括 25 次插入0 次删除
  1. 1 0
      src/mol-util/index.ts
  2. 24 0
      src/mol-util/value-cell.ts

+ 1 - 0
src/mol-util/index.ts

@@ -10,6 +10,7 @@ import StringBuilder from './string-builder'
 import UUID from './uuid'
 import Mask from './mask'
 
+export * from './value-cell'
 export { BitFlags, StringBuilder, UUID, Mask }
 
 export function arrayEqual<T>(arr1: T[], arr2: T[]) {

+ 24 - 0
src/mol-util/value-cell.ts

@@ -0,0 +1,24 @@
+/**
+ * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
+ *
+ * @author David Sehnal <david.sehnal@gmail.com>
+ */
+
+/** A mutable value cell. */
+interface ValueCell<T> { value: T }
+/** Create a mutable value cell. */
+function ValueCell<T>(value: T): ValueCell<T> { return { value }; }
+
+/** An immutable value box that also holds a version of the attribute. */
+interface ValueBox<T> { readonly version: number, readonly value: T }
+/** Create a new box with the specified value and version = 0 */
+function ValueBox<T>(value: T): ValueBox<T>
+/** Create a new box by updating the value of an old box and incrementing the version number. */
+function ValueBox<T>(box: ValueBox<T>, value: T): ValueBox<T>
+function ValueBox<T>(boxOrValue: T | ValueBox<T>, value?: T): ValueBox<T> {
+    if (arguments.length === 2) return { version: (boxOrValue as ValueBox<T>).version + 1, value: value! };
+    return { version: 0, value: boxOrValue as T };
+}
+
+export { ValueCell, ValueBox };
+