Skip to content

Commit

Permalink
feat-model-push-unique (#159)
Browse files Browse the repository at this point in the history
* feat: add `pushUnique` method to ensure an array doesn't contain duplicates

* chore: update files modified by CI [skip ci]

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
  • Loading branch information
snickbit and github-actions[bot] authored Mar 11, 2024
1 parent a2eda17 commit 3a0b541
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
20 changes: 20 additions & 0 deletions packages/model/docs/classes/Model.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ Create a simple object model
- [patch](Model.md#patch)
- [pull](Model.md#pull)
- [push](Model.md#push)
- [pushUnique](Model.md#pushunique)
- [remove](Model.md#remove)
- [set](Model.md#set)
- [toJSON](Model.md#tojson)
Expand Down Expand Up @@ -538,6 +539,25 @@ Push a value to an array path

___

### pushUnique

**pushUnique**(`key`, `value`): [`Model`](Model.md)<`T`, `D`\>

Push a value to an array path if it doesn't exist

#### Parameters

| Name | Type |
| :------ | :------ |
| `key` | [`ModelKey`](../README.md#modelkey) |
| `value` | `any` |

#### Returns

[`Model`](Model.md)<`T`, `D`\>

___

### remove

**remove**(`key`): [`Model`](Model.md)<`T`, `D`\>
Expand Down
15 changes: 13 additions & 2 deletions packages/model/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
uuid,
VariableType
} from '@snickbit/utilities'
import objectPath, {ObjectPathBound} from 'object-path'
import objectPath, {ensureExists, ObjectPathBound} from 'object-path'

export type ModelId = number | string | undefined

Expand Down Expand Up @@ -462,11 +462,22 @@ export class Model<T extends object = any, D = Partial<T>> {
/**
* Push a value to an array path
*/
push(key: ModelKey, ...values) {
push(key: ModelKey, ...values: any[]) {
this.data.push(this.checkKey(key), ...values)
return this
}

/**
* Push a value to an array path if it doesn't exist
*/
pushUnique(key: ModelKey, value: ModelValue) {
const current = this.get(key)
if (!current.includes(value)) {
this.push(key, value)
}
return this
}

/**
* Get the value of a path and remove it
*/
Expand Down

0 comments on commit 3a0b541

Please sign in to comment.