Skip to content

Commit

Permalink
🔭 Initial commit - added createObservable function
Browse files Browse the repository at this point in the history
  • Loading branch information
lukasduspiva committed Feb 23, 2021
0 parents commit 27c5291
Show file tree
Hide file tree
Showing 14 changed files with 4,733 additions and 0 deletions.
11 changes: 11 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# EditorConfig is awesome: https://EditorConfig.org

# top-most EditorConfig file
root = true

# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 2
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
build
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
15
3 changes: 3 additions & 0 deletions .prettierrc.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
singleQuote: true
trailingComma: all
endOfLine: auto
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added

- Kicked off the package with `createObservable` function by [@lukasduspiva](https://github.com/lukasduspiva).

[unreleased]: https://github.com/lukasduspiva/simple-observables/compare/v1.0.0...HEAD
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) Lukas Duspiva

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
96 changes: 96 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# Simple Observables

## Idea

**To have simple JavaScript API for creating and using observable/subscription pattern**, without the need of importing super-heavy libraries such as [RxJS](https://github.com/ReactiveX/rxjs) (which I personally found to be one of the best libraries ever made).

## Getting Started

Via `yarn`:

```cmd
yarn add simple-subscriptions
```

Via `npm`:

```
npm install simple-subscriptions
```

## API `createObservable`

Creates an observable value and returns:

- getter - to get the current value
- setter - to set the current value
- subscribe - to subscribe an observer for value changes
- unsubscribe - to unsubscribe an observer for value changes

### Example

```js
const [getAnimal, setAnimal, subscribe, unsubscribe] = createObservable();

console.log(getAnimal()); // undefined

setAnimal('🐱');
console.log(getAnimal()); // 🐱

const logAnimal = (animal) => console.log(`My current animal is: ${animal}`);
subscribe(logAnimal);

setAnimal('🐶'); // My current animal is: 🐶
setAnimal('🐷'); // My current animal is: 🐷
setAnimal('🦊'); // My current animal is: 🦊

unsubscribe(logAnimal);
console.log(getAnimal()); // 🦊
setAnimal('🐮');
```

### API Design

- **Array destructuring** to let you name your variables:

```js
const [getValue, setValue, subscribe, unsubscribe] = createObservable();

const [getX, setX, subscribeToX, unsubscribeToX] = createObservable();
const [getY, setY, subscribeToY, unsubscribeToY] = createObservable();
// ...
```

- **Multiple subscriptions** support:

```js
const [getValue, setValue, subscribe, unsubscribe] = createObservable();

const logWithA = (value) => console.log(`A: ${value}`);
const logWithB = (value) => console.log(`B: ${value}`);
// ...

subscribe(logWithA);
subscribe(logWithB);
// ...

setValue('Hello!'); // A: Hello!
// B: Hello!

unsubscribe(logWithA);
unsubscribe(logWithB);
// ...
```

- **Initial value** can be provided:

```js
const initialValue = {
preferredGreeting: 'Ahoj',
profession: 'Pirate',
};

const [getValue] = createObservable(initialValue);

console.log(getValue()); // { preferredGreeting: "Ahoj", profession: "Pirate" }
```
3 changes: 3 additions & 0 deletions babel.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
presets: [['@babel/preset-env', { targets: { node: 'current' } }]],
};
26 changes: 26 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"name": "simple-observables",
"version": "0.1.0",
"description": "Simple observable implementation for JavaScript",
"main": "src/index.js",
"scripts": {
"build": "snowpack build",
"pretty": "prettier --write \"./src/**/*.js\" \"*.md\"",
"test": "jest",
"test:watch": "jest --watch"
},
"keywords": [
"observable",
"subscription"
],
"author": "Lukas Duspiva",
"license": "MIT",
"devDependencies": {
"@babel/core": "^7.13.1",
"@babel/preset-env": "^7.13.0",
"babel-jest": "^26.6.3",
"jest": "^26.6.3",
"prettier": "^2.2.1",
"snowpack": "^3.0.13"
}
}
8 changes: 8 additions & 0 deletions snowpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = {
optimize: {
entrypoints: ['./src/index.js'],
bundle: true,
minify: true,
target: 'es2015',
},
};
82 changes: 82 additions & 0 deletions src/__test__/createObservable.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { createObservable } from '../createObservable';

describe('createObservable', () => {
it('should be defined', () => {
expect(createObservable).toBeDefined();
});
it('should be function', () => {
expect(typeof createObservable).toBe('function');
});
it('should return array when called', () => {
expect(Array.isArray(createObservable())).toBe(true);
});
describe('when called with no argument', () => {
describe('when focusing on `getValue` (first desctructured value)', () => {
it('should be a function', () => {
const [getValue] = createObservable();
expect(typeof getValue).toBe('function');
});
it('should return `undefined` when called', () => {
const [getValue] = createObservable();
expect(getValue()).toBe(undefined);
});
});
describe('when focusing on `setValue` (second desctructured value)', () => {
it('should be a function', () => {
const [_getValue, setValue] = createObservable();
expect(typeof setValue).toBe('function');
});
it('when called with a value, the value should be then returned by `getValue`', () => {
const [getValue, setValue] = createObservable();
setValue(':-)');
expect(getValue()).toBe(':-)');
});
});
describe('when focusing on `subscribe` (third desctructured value)', () => {
it('should be a function', () => {
const [_getValue, _setValue, subscribe] = createObservable();
expect(typeof subscribe).toBe('function');
});
describe('when called with a "observer" function', () => {
it('the function should be invoked by argument supplied to `setValue` once it is called', () => {
const observer = jest.fn();
const [_getValue, setValue, subscribe] = createObservable();
subscribe(observer);
setValue(':-P');
expect(observer.mock.calls.length).toBe(1);
expect(observer.mock.calls[0][0]).toBe(':-P');
});
});
});
describe('when focusing on `unsubscribe` (fourth desctructured value)', () => {
it('should be a function', () => {
const [
_getValue,
_setValue,
_subscribe,
unsubscribe,
] = createObservable();
expect(typeof unsubscribe).toBe('function');
});
it('should remove the effect of subscription, so once `setValue` is called it no longer invokes observer', () => {
const observer = jest.fn();
const [getValue, setValue, subscribe, unsubscribe] = createObservable();
subscribe(observer);
setValue(':-X');
unsubscribe(observer);
setValue(':-S');
expect(getValue()).toBe(':-S');
expect(observer.mock.calls.length).toBe(1);
expect(observer.mock.calls[0][0]).toBe(':-X');
});
});
});
describe('when called with a argument', () => {
describe('when focusing on `getValue` (first desctructured value)', () => {
it('should return the passed argument', () => {
const [getValue] = createObservable(':-O');
expect(getValue()).toBe(':-O');
});
});
});
});
24 changes: 24 additions & 0 deletions src/createObservable.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
export function createObservable(initialValue) {
let value = initialValue;
let subscriptions = [];

function getValue() {
return value;
}
function setValue(newValue) {
value = newValue;
subscriptions.forEach((subscription) => subscription(newValue));
}

function subscribe(subscription) {
subscriptions = [...subscriptions, subscription];
}

function unsubscribe(subscription) {
subscriptions = subscriptions.filter(
(testedSubscription) => testedSubscription !== subscription,
);
}

return [getValue, setValue, subscribe, unsubscribe];
}
5 changes: 5 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export { createObservable } from './createObservable';

export default {
createObservable,
};
Loading

0 comments on commit 27c5291

Please sign in to comment.