UNPKG

functionalscript

Version:

FunctionalScript is a purely functional subset of JavaScript

64 lines (63 loc) 2.26 kB
import { next, flat, map } from "../types/list/module.f.js"; import { concat } from "../types/string/module.f.js"; import { at } from "../types/object/module.f.js"; import { compose, fn } from "../types/function/module.f.js"; import { objectWrap, arrayWrap, stringSerialize, numberSerialize, nullSerialize, boolSerialize } from "./serializer/module.f.js"; const { entries } = Object; export const setProperty = value => { const f = path => src => { const result = next(path); if (result === null) { return value; } const srcObject = (src === null || typeof src !== 'object' || src instanceof Array) ? {} : src; const { first, tail } = result; return { ...srcObject, [first]: f(tail)(at(first)(srcObject)) }; }; return f; }; const colon = [':']; export const serialize = sort => { const propertySerialize = ([k, v]) => flat([ stringSerialize(k), colon, f(v) ]); const mapPropertySerialize = map(propertySerialize); const objectSerialize = fn(entries) .then(sort) .then(mapPropertySerialize) .then(objectWrap) .result; const f = value => { switch (typeof value) { case 'boolean': { return boolSerialize(value); } case 'number': { return numberSerialize(value); } case 'string': { return stringSerialize(value); } default: { if (value === null) { return nullSerialize; } if (value instanceof Array) { return arraySerialize(value); } return objectSerialize(value); } } }; const arraySerialize = compose(map(f))(arrayWrap); return f; }; /** * The standard `JSON.stringify` rules determined by * https://262.ecma-international.org/6.0/#sec-ordinary-object-internal-methods-and-internal-slots-ownpropertykeys */ export const stringify = sort => compose(serialize(sort))(concat); export const parse = JSON.parse; export const isObject = (value) => typeof value === 'object' && value !== null && !(value instanceof Array);