Code Monkey home page Code Monkey logo

z's People

Contributors

asakaev avatar bysabi avatar canac avatar dzcpy avatar idcmardelplata avatar jgretz avatar koleok avatar leonardiwagner avatar lyrkan avatar paulojean avatar pvorona avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

z's Issues

Installation on Windows/without git not working due to git checkout

Hello there,

There seems to be an issue in the package.json.
Currently, you have a fixed git checkout to js-function-reflector but that requires the user to have git available.

While this is no problem for your all-day developer, this means you need git at install-time. So including z into software that is used by the average software "user" will become difficult (of course, we can question how often the average user uses npm).
Also, this makes it hard to use z in environments where you wish to have as few dependencies as possible, such as docker containers or strict production machines.
Another argument against having git references is that you might wish to have "the correct" version in your software. Meaning when I create a package today, I want it to behave the same tomorrow to ensure the working of my package.

I can actually not reproduce this but a colleague had this issue. I suppose you can enforce it by removing git from your system and try to install z.

What are your thoughts on this?

You're accidentally stealing a name and logo

There's already something in active use called z and it has a very similar logo

It's a mathematical constraint system for proving software, and a big chunk of it is about pattern matching

When golang took the same name as the existing high quality language go, the existing language disappeared forever, despite that it had several compilers and books

Please consider renaming your project. The Way of Z deserves to live, and formal methods are already much too rare

Matching on types incorrectly identifies an object as a String

Just tried the following on Node.js v9.8.0:

▶ node
> const { matches } = require('z')
undefined
> matches({ x: 3 })((x = String) => `${x} is a String`, (x = Object) => 'Object')
'[object Object] is a String'
> const _ = require('lodash')
undefined
> _.isString({x: 3})
false

Source code question

Hello, I've been browsing through source code trying to understand how the thing works and got question considering following function:

const matches = (subjectToMatch) =>
  function () {
    const functions = Object.keys(arguments).map(key => arguments[key])

    return resolveMatchFunctions(subjectToMatch, functions)
  }

Could you explain why is it using Object.keys / arguments instead of using rest args?

const matches = (subjectToMatch) => (...functions) => 
  resolveMatchFunctions(subjectToMatch, functions)

I cant find any test explaining this thing.

Flip around order of arguments

Thank you for a very useful library. It's a bit late to bring this up I think, but I thought I'd open an issue anyway; it seems like the current order of arguments is not great for partial application. From the README examples:

const compress = (numbers) => {
  return matches(numbers)(
    (x, y, xs) => x === y
      ? compress([x].concat(xs))
      : [x].concat(compress([y].concat(xs))),
    (x, xs) => x // stopping condition
  )
}

but if it accepted the case matchers first, it could just be:

const compress = matches(
  (x, y, xs) => x === y
    ? compress([x].concat(xs))
    : [x].concat(compress([y].concat(xs))),
  (x, xs) => x // stopping condition
)

It's not hard to define a flipped around version wherever I use it, but it'd be handy if the library just exported a different version of matches that took arguments in that order.

not matching strings

'text'.matches(
      (x = 'text') => 'a'
    )

it isn't returning a , is throwing can't match anything for: text instead

Match on presence of key

My most common use case is matching on the presence of a key in an object and binding a variable to it de-structured style, I noticed this idea made it into the tc39 pattern matching proposal and was wondering if you had plans to implement anything similar in z?

example from proposal:

match (obj) {
    { x }: /* match an object with x */,
    { x, ... y }: /* match an object with x, stuff any remaining properties in y */,
    { x: [] }: /* match an object with an x property that is an empty array */,
    { x: 0, y: 0 }: /* match an object with x and y properties of 0 */
}

I'd be glad to take a crack at it and send a PR if not 😀

Help, with documentation.

Reamde says

matches([1])(
  (a, b,  tail)      => 'Will not match here',
  (a = 2, tail = []) => 'Will not match here',
  (a = 1, tail)      => 'Will match here, tail = []'
)

but

     let a = Z.matches([1])(
            (a = 1, tail) => {
                return 'a = 1, b = []'
            }
        );
        console.log("a");
        console.log(a); // undefined

        let b = Z.matches([1])(
            (b, tail = []) => {
                return 'a = 1, b = []'
            }
        );
        console.log("b");
        console.log(b); //  a = 1, b = []

How is this possible?

I see you're using js-function-reflector but does that mean you need to use babel-preset-es2015-reflector?

Don't use prototype

It would be better to use

var matches = require('z')

var myReverse = list => {
  return matches(list,  // first param for `matches` is an Array, String, etc.
    ()           => [], 
    (head, tail) => myReverse(tail).concat(head)
  )
}

myReverse([1, 2, 3, 4, 5]) //[5, 4, 3, 2, 1])

or

var matches = require('z')

var myReverse = list => {
  return matches(list)(  // `matches` returns a function to use patterns
    ()           => [], 
    (head, tail) => myReverse(tail).concat(head)
  )
}

myReverse([1, 2, 3, 4, 5]) //[5, 4, 3, 2, 1])

instead of

require('z')

var myReverse = list => {
  return list.matches (  // uses prototype
    ()           => [],
    (head, tail) => 
  )
}

myReverse([1, 2, 3, 4, 5]) //[5, 4, 3, 2, 1])

does not work with typescript

Strange but when I use some of the snippets with typescript, it always returns the result of the first param. For example

import {matches} from 'z';

const person = { name: 'Maria' }
matches(person)(
  (x = { name: 'John' }) => console.log('John you are not welcome!'),
  (x)                    => console.log(`Hey ${x.name}, you are welcome!`)
)

returns John you are not welcome.

Does not work if match value comes from a variable

e.g:

#!/usr/bin/env node
const { matches } = require('z')

const FILTERS = {
  CATEGORY: 'CATEGORY',
  PRICE: 'PRICE',
  COLOR: 'COLOR',
  ONLY_NEW: 'ONLY_NEW',
  ONLY_IN_DISCOUNT: 'ONLY_IN_DISCOUNT'
}

const _30DaysAgo = Date.now() - 1000 * 60 * 60 * 24 * 30
const convertOptionsToQuery = filterOptions => matches(filterOptions.by)(
  (b = FILTERS.CATEGORY) => ({ category: filterOptions.value }),
  (b = FILTERS.COLOR) => ({ colors: filterOptions.value }),
  (b = FILTERS.PRICE) => ({ price: { $gte: filterOptions.value[0], $lte: filterOptions.value[1] } }),
  (b = FILTERS.ONLY_NEW) => ({ createdAt: { $gte: new Date(_30DaysAgo) } }),
  (b = FILTERS.ONLY_IN_DISCOUNT) => ({ isInDiscount: true }),
  (b) => ({})
)

convertOptionsToQuery({ by: 'CATEGORY', value: 'shirts' })

// ReferenceError: FILTERS is not defined

Strangely enough, it only happens if the code is ran as a file, if it is ran in the REPL it works.

This error seems to be related to js-function-reflector.

it's not "native", it's "vanilla"

"native" nowadays means "a system app" -- mobile or desktop, i.e. "does not depend on a web-browser"

what you wanted to say is "vanilla" -- b/c it dosnt need babel, webpack or a WASM compiler

async/await example

Let's say we have this:

matches(x)(
  async (x, xs) => {
    const thing = await somethingElse()
    ...
  },
  (x) => {

  },
)

Will this even...?

Update dependencies

  • Update dependencies version
  • Check for dependencies securities fixes
  • Use js-function-reflector as npm package instead git link

Working with "dynamic" objects

Hey there,

I'm trying to get a grip on this library and would love to use it with objects.
Currently, I'm trying to parse a version and based on the object's major/minor/patch, do different things:

'use strict';

const matches = require('z').matches;
const semver = require('semver-utils');

const manual = {
  major: '1',
};
const parsed = semver.parse('1.0.0');

// Always default
matches(parsed).call(parsed,
  (x = {major: '1'}) => console.log('m_one'),
  (x = {major: '2'}) => console.log('m_two'),
  (x = null) => console.log('default'),
  (x) => console.dir(x)
)

// Always 1 but static :(
matches(manual).call(manual,
  (x = {major: '1'}) => console.log('m_one'),
  (x = {major: '2'}) => console.log('m_two'),
  (x = null) => console.log('default'),
  (x) => console.dir(x)
)

Following the sample from the documentation results that Marie is welcome - it works as expected and my implementation for manual does, too. But that is basic stuff I don't need.
I'd like to patternmatch things dynamically. I'm not sure if it's possible of if I'm just using the library in the wrong manner.

I've read about the .call approach in other issues but this doesn't seem to help.

Help is much appreciated!

Not work with Babel

Transformed code with Babel not work.

Probably is due this is not set: from js-function-reflector doc:

var functionReflector = require('js-function-reflector');
// If you are using babel transpiler
functionReflector = reflector.compiler('babel-preset-es2015');

Exhaustivity checking

Have an option that checks if the matching is exhaustive, and if it isn't then have it immediately throw an error that the matching isn't exhaustive.

z is slow because it reparses function source code every time

I mean pattern matching is cool when it's a core language feature, but...

Test Code

const { matches } = require('z')
 
const zCompress = numbers => matches(numbers)(
  (x, y, xs) => x === y
    ? zCompress([x].concat(xs))
    : [x].concat(zCompress([y].concat(xs))),
  (x, xs) => x // stopping condition
)

const jsCompress = numbers => numbers.filter((n, i) => n !== numbers[i - 1])

const input = [1, 1, 2, 3, 4, 4, 4]

const count = 100000
function time(fn) {
  const start = Date.now()
  for (let i = 0; i < count; i++) fn(input)
  return Date.now() - start
}
 
const zTime = time(zCompress)
const jsTime = time(jsCompress)

console.log('z: ', zTime + ' ms')
console.log('js: ', jsTime + ' ms')

console.log(`z took ${zTime / jsTime} times longer`)

Results

MacBook Pro Mid 2014, macOS 10.15.5. Node 12.16.2.

$ node index.js 
z:  12560 ms
js:  23 ms
z took 546.0869565217391 times longer

Matching doesn't work on strings

Hello!

First of all, great library, thank you!

I just introduced z (version 1.0.8) to a project and I cannot seem to get it to work with strings. I created a sandbox in which I recreated the issue I faced. It also includes two tests from the test suite that don't work as expected. I'm not familiar with the source code but anyways let me know if I can be of help fixing this issue.

Here is the sandbox: https://codesandbox.io/s/w6kql5km47
Thank you in advance for your time looking into this!

Using rest params?

Nice lib! Docs say

(x) => {} matches an array with a single element eg.: [1], [[1, 2, 3]](array with a single array), matches single character eg.: 'x' or matches a single number eg.:1
(x, xs) => {} matches array with more than one element. First parameter is the first element (head), second is others (tail)

Couldn't we use rest params to be more precise? If (x) => {} matches a single element I'd expect (x, y) => {} to match exactly two elements (array.length === 2). I'd use (x, ...xs) => {} to match an array with more than one element (first element (head) and others (tail)).

Multi-Character global condition match failure

I'm running into what may be a conceptual issue rather than an actual issue. Are multi-character match variables supported?

E.g.

let string = "test"; match(string)( (s) => { console.log(s); } )

Executes as expected logging

test

but

let string = "test"; match(string)( (str) => { console.log(str); } )

generates no output.

not working properly

trying to find length of a list

const findLength = (list) => matches(list)(
  (x = [])  => 0,
  (_, xs)       => 1 + findLength(xs)
)

nor

const findLength = (list) => matches(list)(
  (x = [], xs)  => 0,
  (_, xs)       => 1 + findLength(xs)
)

works

using Z with redux?

Hey so I'm testing out the possibility of using z with the reducer in redux with the following code:

export const reducer = (state, action) =>
  matches(action.type)(
    (x = 'ADD') => ({...state, counter: state.counter+1}),
    (x = 'REM') => ({...state, counter: state.counter-1}),
    x => {console.log(`no state ${x}`); return state}
  );

and then in then in my main app (a counter) I have the following:

const Counter = ({value, onIncrement, onDecrement}) =>
  <div>
    <button onClick={onIncrement}>
      +
    </button>
    {value}
    <button onClick={onDecrement}>
      -
    </button>
  </div>

const App = ({state, dispatch}) =>{
  console.log(state)
  return (<div>
    <Counter value={state.counter} onDecrement={() => dispatch({type: "REM"})} onIncrement={() => dispatch({type: "ADD"})}/>
  </div>)
}
export default connect(state => ( {state: state} ))(App);

but when I click a button returns no state REM, in the stack trace I saw that subjectToMatch = "REM".

Function reflector does not handle the case of using object-based value

I have code like:

types.js

const Types = Object.freeze({
  A: 'a',
  B: 'b',
});

module.exports = Object.freeze({
  ...Types,
  Types: Object.values(Types),
});

index.js

const Types = require('./types');

const { matches } = require('z');

const match = matches('a')(
  (x = Types.A) => 'matched A',
  (x = Types.B) => 'matched B',
);

console.info(match);

and the expected behavior is to just work as the x is assigned by constant, but it seems not so just throwing an TypeError which looks like:

TypeError: Cannot read property 'A' of undefined
    at eval (eval at Parser.pushBuffer (C:\Users\suhun\Downloads\z-test\node_modules\js-function-reflector\argument_parser.js:96:22), <anonymous>:1:13)
    at Parser.pushBuffer (C:\Users\suhun\Downloads\z-test\node_modules\js-function-reflector\argument_parser.js:96:22)
    at Parser.parse (C:\Users\suhun\Downloads\z-test\node_modules\js-function-reflector\argument_parser.js:67:14)
    at module.exports (C:\Users\suhun\Downloads\z-test\node_modules\js-function-reflector\header_parser.js:10:21)
    at reflector (C:\Users\suhun\Downloads\z-test\node_modules\js-function-reflector\index.js:34:30)
    at module.exports (C:\Users\suhun\Downloads\z-test\node_modules\z\src\getMatchDetails.js:4:29)
    at resolveMatchFunctions (C:\Users\suhun\Downloads\z-test\node_modules\z\src\z.js:9:26)
    at functions (C:\Users\suhun\Downloads\z-test\node_modules\z\src\z.js:44:3)
    at Object.<anonymous> (C:\Users\suhun\Downloads\z-test\index.js:5:27)
    at Module._compile (internal/modules/cjs/loader.js:654:30)

I believe this should be filed in the js-function-reflector but I do it here because z has a dependency on it, which appears to be maintained by you.

Do you need a new logo?

Hello, I like to contribute with graphic designs, in opensource projects, so if you need something from me like a new logotype or something else just say it, Im here ready to help you.

Greetings!
Nuno Jesus

Type definitions?

So, I'm about to start using this lib in a project, but I figured out that there is no type declaration file for the project or a @types/z package

Matching Consts

Using z in a Redux project, I was very surprised to find that matches doesn't work with atomic consts:

const { matches } = require('z')

const FOO = 'foo'

matches(FOO)(
  (x = FOO) => console.log('foo is foo!'),
  (x)       => console.log('foo is not foo???')
)

This code results in "foo is not foo???", which is (ahem) not really what I was expecting.

I haven't dug into the source code to see how z works its magic, but it seems like this would be a really common use case.

Current problem with `z`

When I found z I wanted to improve it, bringing pattern matching to javascript will be a breakthrough. First of all I wanted to understand how it was implemented and what is better than reimplement it from scratch. A few days later I abandoned the idea because in my opinion this library has no future. I report the problems I have encountered.

z bases its logic on functions "reflection?". The trick of reflection is to convert the function to string, Function.toString() and then extract the match patterns from there. You can make an acceptably fast parser to save performance problems but this is not the main problem.

When we convert the function to string to extract the default values ​​what we are doing is "serialize" the function. The problem is when we "deserialize", for this we need to use eval that is slow and has serious security problems and the worst thing is that we can only deserialize the build-in types, forget about doing match of something like (x = MyType) => x

The other option is to create a transform plugin for Babel similar to sparkler (made with sweet.js) https://github.com/natefaubion/sparkler
But I think it's best for the bright minds of https://github.com/tc39/proposal-pattern-matching/blob/master/README.md#object-patterns to do so.

I for my part have a third option and wanted to share it here in case z crew want to follow this path, before make a separate library. I share a piece of code to see how it might look. There are no reflections or parsers, only vanilla js and the sintax is different

function matcher(v) {
    return function (...funcs) {
        const firstCall = funcs.map(fn => fn())
        for (let i = 0; i < firstCall.length; i++) {
            const [fn, x] = firstCall[i];
         
          // TODO: this the most simply matcher
          // we need dedicate matchers for all javascript types
          if (v === x) {
                return fn(x)
            }
        
      }
    }
}

function match(x, ...y) {
  return function(fn) {
     return [fn, x, ...y];
  }
}


// New sintax
const a = matcher(5)(
    (x) => match(x)(console.log),
    (x = 3) => match(x)(console.log),
    (x = 5) => match(x)(console.log)
)

What is your opinion/decision ?? @leonardiwagner @Koleok

Support unnamed desctructured parameters

Currently I'm investigating the ability of implementing the following:

match({ a: 1, b: 2 })(
  ({ a = 3, b = 4 }) => 'doesnt match',
  ({ a = 1, ...c }) => 'matches with c = { b: 2 }',
  ({ a, b }, { c, d }) => 'doesnt match',
)

Compare to previous version:

match({ a: 1, b: 2 })(
  (x = { a = 3, b = 4 }) => 'doesnt match',
  (x = { a = 1, ...c }) => 'matches with c = { c: 2 }',
  (x = { a, b }, y = { c, d }) => 'doesnt match',
)

So the unneeded parameter x is removed. I can't find any closed issue addressed this idea. What's your thoughts on this thing?

a unfinnish work ...

Relate to previous issues: #16 #22 #23

I start to research another way to implement pattern matching, I make some progress but I don´t have more time to continue.

Is really hard to do a rich pattern matching library and retain a user friendly API. IMO create a parallel library to current tc39/proposal-pattern-matching is not the way to go. But I think this unfinnish work could be use like a ES5 pollyfil of future pattern-matching Babel transform. It seem another developers are made some progress in this direction: https://github.com/Jamesernator/pattern-match

Any way here is the repos of the working implementation. They are two packages:

  • core-z is the assertion engine
  • z is the assertion library

Right now the code is working but will need create more assertion functions for match Objects, Arrays, ...

I hadn´t write docs beyond code comments and working test examples, sorry.

I hope this could be useful ...

Issue with example on the web page

Thanks for this library, it's really nice.

If found an issue with an example on the web page.

If you run this code, nothing matches, it returns undefined:

matches([1])(
  (a, b,  tail)      => 'Will not match here',
  (a = 2, tail = []) => 'Will not match here',
  (a = 1, tail)      => 'Will match here, tail = []'
)

I would have expected the 3rd case to match.

Did the library change and the docs haven't been updated?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.