Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add typeArray and allow passing equal function to bindableDerived #175

Merged
merged 1 commit into from
Oct 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion core/lib/services/checks.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {describe, expect, test} from 'vitest';
import {isBoolean, isFunction, isNumber, clamp, isString} from './checks';
import {isBoolean, isFunction, isNumber, clamp, isString, isArray} from './checks';

describe('Checks', () => {
test(`'isNumber' should check if value is a number`, () => {
Expand Down Expand Up @@ -79,6 +79,25 @@ describe('Checks', () => {
expect(isString(() => {})).toBe(false);
});

test(`'isArray' should check if the value is an array`, () => {
expect(isArray(true)).toBe(false);
expect(isArray(false)).toBe(false);
expect(isArray(0)).toBe(false);
expect(isArray(1)).toBe(false);
expect(isArray(1.1)).toBe(false);
expect(isArray('1')).toBe(false);
expect(isArray('0')).toBe(false);
expect(isArray('1.1')).toBe(false);
expect(isArray(undefined)).toBe(false);
expect(isArray(null)).toBe(false);
expect(isArray({})).toBe(false);
expect(isArray([])).toBe(true);
expect(isArray(NaN)).toBe(false);
expect(isArray(Infinity)).toBe(false);
expect(isArray(-Infinity)).toBe(false);
expect(isArray(() => {})).toBe(false);
});

test(`'getValueInRange' should return a value is within a specific range`, () => {
expect(clamp(1, 5)).toBe(1);
expect(clamp(-1, 5)).toBe(0);
Expand Down
6 changes: 6 additions & 0 deletions core/lib/services/checks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ export function isString(value: any): value is string {
return typeof value === 'string';
}

/**
* an array type guard
* @returns true if the value is an array
*/
export const isArray = Array.isArray;

// TODO should we check that max > min?
/**
* Clamp the value based on a maximum and optional minimum
Expand Down
36 changes: 35 additions & 1 deletion core/lib/services/stores.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,9 @@ describe(`Stores service`, () => {
const valueMax$ = writable(2);

const value$ = bindableDerived(onValueChange$, [dirtyValue$, valueMax$], ([dirtyValue, valueMax]) => Math.min(dirtyValue, valueMax));
const unsubscribe = value$.subscribe((value) => values.push(value));
const unsubscribe = value$.subscribe((value) => {
values.push(value);
});
expect(values).toEqual([1]);
valueMax$.set(3); // no change
expect(onChangeCalls).toEqual([]);
Expand Down Expand Up @@ -442,5 +444,37 @@ describe(`Stores service`, () => {
expect(values).toEqual([1, 2]);
unsubscribe();
});

test(`should override equals function`, () => {
const onChangeCalls: number[][] = [];
const values: number[][] = [];
const dirtyValue$ = writable([1]);
const onValueChange$ = writable((value: number[]) => {
onChangeCalls.push(value);
});

const value$ = bindableDerived(
onValueChange$,
[dirtyValue$],
([dirtyValue]) => dirtyValue.map((dv) => Math.floor(dv)),
(a, b) => a.every((val, index) => val === b[index])
);
value$.subscribe((value) => values.push(value));
expect(values).toEqual([[1]]);

dirtyValue$.set([1]); // no change
expect(onChangeCalls).toEqual([]);
expect(values).toEqual([[1]]);

dirtyValue$.set([2.5]);
expect(dirtyValue$()).toEqual([2]);
expect(onChangeCalls).toEqual([[2]]);
expect(values).toEqual([[1], [2]]);
divdavem marked this conversation as resolved.
Show resolved Hide resolved

dirtyValue$.set([5.6, 7.8]);
expect(dirtyValue$()).toEqual([5, 7]);
expect(onChangeCalls).toEqual([[2], [5, 7]]);
expect(values).toEqual([[1], [2], [5, 7]]);
});
});
});
32 changes: 18 additions & 14 deletions core/lib/services/stores.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,21 +321,25 @@
export const bindableDerived = <T, U extends [WritableSignal<T>, ...StoreInput<any>[]]>(
onChange$: ReadableSignal<(value: T) => void>,
stores: U,
adjustValue: (arg: StoresInputValues<U>) => T
adjustValue: (arg: StoresInputValues<U>) => T,
equal = (currentValue: T, newValue: T) => newValue === currentValue
) => {
let currentValue = stores[0]();
return derived(stores, (values) => {
const newValue = adjustValue(values);
const rectifiedValue = newValue !== values[0];
if (rectifiedValue) {
stores[0].set(newValue);
}
if (rectifiedValue || newValue !== currentValue) {
currentValue = newValue;
// TODO check if we should do this async to avoid issue
// with angular and react only when rectifiedValue is true?
onChange$()(newValue);
}
return newValue;
return derived(stores, {
derive(values) {
const newValue = adjustValue(values);
const rectifiedValue = !equal(values[0], newValue);
if (rectifiedValue) {
stores[0].set(newValue);

Check warning on line 333 in core/lib/services/stores.ts

View check run for this annotation

Codecov / codecov/patch

core/lib/services/stores.ts#L333

Added line #L333 was not covered by tests
}
if (rectifiedValue || !equal(currentValue, newValue)) {
currentValue = newValue;
// TODO check if we should do this async to avoid issue
// with angular and react only when rectifiedValue is true?
onChange$()(newValue);
}
return newValue;
},
equal,
});
};
38 changes: 38 additions & 0 deletions core/lib/services/writables.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import {writable} from '@amadeus-it-group/tansu';
import type {SpyInstance} from 'vitest';
import {beforeEach, describe, expect, test, vi} from 'vitest';
import {writableWithDefault} from './stores';
import {typeArray} from './writables';

describe(`Writables service`, () => {
const equal = typeArray.equal!;
let consoleErrorSpy: SpyInstance<Parameters<typeof console.error>, ReturnType<typeof console.error>>;

beforeEach(() => {
consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
});

test(`should support typeArray`, () => {
const config$ = writable([0]);
const store$ = writableWithDefault<number[]>([0], config$, typeArray);
// set the wrong value
store$.set(100 as any);
expect(consoleErrorSpy).toHaveBeenCalledWith('Not setting invalid value', 100);
// the store is not updated with the wrong value
expect(store$()).toStrictEqual([0]);

const testArray = [15, 20];
store$.set(testArray);

expect(store$()).toBe(testArray);
});

test(`typeArray equal function should compare values`, () => {
divdavem marked this conversation as resolved.
Show resolved Hide resolved
expect(equal([15, 15], [15, 15])).toBe(true);
expect(equal([15, 15], [15, 10])).toBe(false);
const arr = [15, 15];
expect(equal(arr, arr)).toBe(true);
expect(equal([15], [15, 15])).toBe(false);
expect(equal([15, 15], [15])).toBe(false);
});
});
16 changes: 15 additions & 1 deletion core/lib/services/writables.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {isBoolean, isFunction, isNumber, isString} from './checks';
import {isArray, isBoolean, isFunction, isNumber, isString} from './checks';
import type {WritableWithDefaultOptions} from './stores';
import {INVALID_VALUE} from './stores';

Expand All @@ -23,3 +23,17 @@
normalizeValue: testToNormalizeValue(isFunction),
equal: Object.is,
};

export const typeArray: WritableWithDefaultOptions<any[]> = {
normalizeValue: testToNormalizeValue(isArray),
equal: (a, b) => {
divdavem marked this conversation as resolved.
Show resolved Hide resolved
if (a === b) {
return true;

Check warning on line 31 in core/lib/services/writables.ts

View check run for this annotation

Codecov / codecov/patch

core/lib/services/writables.ts#L31

Added line #L31 was not covered by tests
} else {
if (a?.length !== b?.length) {
return false;

Check warning on line 34 in core/lib/services/writables.ts

View check run for this annotation

Codecov / codecov/patch

core/lib/services/writables.ts#L34

Added line #L34 was not covered by tests
}
return a.every((val, index) => val === b[index]);

Check warning on line 36 in core/lib/services/writables.ts

View check run for this annotation

Codecov / codecov/patch

core/lib/services/writables.ts#L36

Added line #L36 was not covered by tests
}
},
};
Loading