Comparing version 0.0.4 to 0.0.5
102
cake-hash.js
@@ -8,3 +8,3 @@ /*! | ||
* @license MIT | ||
* @version 0.0.4 | ||
* @version 0.0.5 | ||
*/ | ||
@@ -285,42 +285,26 @@ (function (global, factory) { | ||
function get(data, path) { | ||
var defaultValue = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2]; | ||
function trim(input) { | ||
return input.replace(/^\s+|\s+$/g, ""); | ||
} | ||
var parts = undefined, | ||
val = undefined; | ||
function split(input, separator) { | ||
var tokens = (input + "").split(separator); | ||
var results = []; | ||
var previousValue = null; | ||
if (!isCollection(data)) { | ||
return defaultValue; | ||
} | ||
if (empty(data) || path == null || path === "") { | ||
return defaultValue; | ||
} | ||
if (isString(path) || isNumeric(path)) { | ||
parts = (path + "").split("."); | ||
} else { | ||
if (!isArray(path)) { | ||
return defaultValue; | ||
} | ||
parts = path; | ||
} | ||
val = isCollection(data) ? clone(data) : data; | ||
each(parts, function (v) { | ||
if (isCollection(val) && hasProp(val, v)) { | ||
val = val[v]; | ||
each(tokens, function (token) { | ||
if (/^.*\\$/.test(token)) { | ||
previousValue = token; | ||
} else { | ||
val = defaultValue; | ||
return false; | ||
if (previousValue != null) { | ||
token = previousValue.slice(0, previousValue.length - 1) + separator + token; | ||
previousValue = null; | ||
} | ||
results.push(token); | ||
} | ||
}); | ||
return val; | ||
return results; | ||
} | ||
function trim(input) { | ||
return input.replace(/^\s+|\s+$/g, ""); | ||
} | ||
function tokenize(str) { | ||
@@ -350,10 +334,15 @@ var separator = arguments.length <= 1 || arguments[1] === undefined ? "," : arguments[1]; | ||
} | ||
// console.log(depth, buffer); | ||
if (tmpOffset !== -1) { | ||
buffer += str.substr(offset, tmpOffset - offset); | ||
var char = str.substr(tmpOffset, 1); | ||
if (!depth && char === separator) { | ||
if (!depth && char === separator && str.substr(tmpOffset - 1, 1) !== "\\") { | ||
results.push(buffer); | ||
buffer = ""; | ||
} else { | ||
buffer += char; | ||
if (depth === 0 && /^.*\\$/.test(buffer)) { | ||
buffer = buffer.slice(0, buffer.length - 1) + char; | ||
} else { | ||
buffer += char; | ||
} | ||
} | ||
@@ -461,2 +450,38 @@ if (left !== right) { | ||
function get(data, path) { | ||
var defaultValue = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2]; | ||
var parts = undefined, | ||
val = undefined; | ||
if (!isCollection(data)) { | ||
return defaultValue; | ||
} | ||
if (empty(data) || path == null || path === "") { | ||
return defaultValue; | ||
} | ||
if (isString(path) || isNumeric(path)) { | ||
parts = split(path, "."); | ||
} else { | ||
if (!isArray(path)) { | ||
return defaultValue; | ||
} | ||
parts = path; | ||
} | ||
val = isCollection(data) ? clone(data) : data; | ||
each(parts, function (v) { | ||
if (isCollection(val) && hasProp(val, v)) { | ||
val = val[v]; | ||
} else { | ||
val = defaultValue; | ||
return false; | ||
} | ||
}); | ||
return val; | ||
} | ||
function extract(data, path) { | ||
@@ -480,3 +505,3 @@ if (!isCollection(data)) { | ||
if (path.indexOf("[") < 0) { | ||
tokens = path.split("."); | ||
tokens = split(path, "."); | ||
} else { | ||
@@ -692,2 +717,3 @@ tokens = tokenize(path, ".", "[", "]"); | ||
each(input, function (val, key) { | ||
key = (key + "").split(separator).join("\\" + separator); | ||
path = currentPath == null ? key : "" + currentPath + separator + key; | ||
@@ -713,3 +739,3 @@ if (isCollection(val)) { | ||
each(data, function (value, flat) { | ||
var keys = (flat + "").split(separator).reverse(); | ||
var keys = split(flat, separator).reverse(); | ||
var child = {}; | ||
@@ -736,3 +762,3 @@ child[keys.shift()] = value; | ||
var VERSION = "0.0.4"; | ||
var VERSION = "0.0.5"; | ||
@@ -739,0 +765,0 @@ // Core |
@@ -8,4 +8,4 @@ /*! | ||
* @license MIT | ||
* @version 0.0.4 | ||
* @version 0.0.5 | ||
*/ | ||
!function(global,factory){"object"==typeof exports&&"undefined"!=typeof module?module.exports=factory():"function"==typeof define&&define.amd?define(factory):global.CakeHash=factory()}(this,function(){"use strict";function getType(obj){return null==obj?obj+"":"object"===("undefined"==typeof obj?"undefined":babelHelpers["typeof"](obj))||"function"==typeof obj?classTypes[Object.prototype.toString.call(obj)]||"object":"undefined"==typeof obj?"undefined":babelHelpers["typeof"](obj)}function isArray(obj){return Array.isArray(obj)}function isObject(obj){return!isArray(obj)&&"object"===getType(obj)}function isNumber(obj){return"number"===getType(obj)}function isString(obj){return"string"===getType(obj)}function isBoolean(obj){return"boolean"===getType(obj)}function isCollection(obj){return isArray(obj)||isObject(obj)}function isNumeric(obj){var type=getType(obj);return("number"===type||"string"===type)&&obj-parseFloat(obj)+1>=0}function isInteger(obj){var type=getType(obj);return("number"===type||"string"===type)&&/^([1-9]\d*|0)$/.test(obj)}function empty(obj){return isArray(obj)?0===obj.length:isObject(obj)?0===Object.keys(obj).length:isNumeric(obj)?0===parseFloat(obj):!obj}function hasProp(obj,key){return obj&&obj.hasOwnProperty(key)}function clone(obj){var _isArray=isArray(obj),_isObject=isObject(obj);if(_isArray||_isObject){var result=_isArray?[]:{},key=void 0,val=void 0;for(key in obj)hasProp(obj,key)&&(val=obj[key],isCollection(val)&&(val=clone(val)),result[key]=val);return result}}function merge(obj,source){var deep=arguments.length<=2||void 0===arguments[2]?!1:arguments[2];return each(source,function(value,key){deep&&hasProp(obj,key)&&isCollection(value)?merge(obj[key],value,deep):obj[key]=value}),obj}function each(obj,iterate,context){if(null==obj)return obj;if(context=context||obj,isObject(obj)){for(var key in obj)if(hasProp(obj,key)&&iterate.call(context,obj[key],key)===!1)break}else if(isArray(obj)){var i=void 0,length=obj.length;for(i=0;length>i&&iterate.call(context,obj[i],i)!==!1;i++);}return obj}function arrayCombine(keys,values){var data={},keyCount=keys&&keys.length,i=0,key=void 0;if(!(isCollection(keys)&&isCollection(values)&&isNumber(keyCount)&&isNumber(values.length)&&keyCount))return null;if(keyCount!==values.length)return null;for(i=0;keyCount>i;i++)key=keys[i],isInteger(key)&&(key=parseInt(key,10)),data[key]=values[i];return objToArray(data)}function arrayFill(startIndex,num,mixedVal){var key=void 0,arr=[];if(!isNaN(startIndex)&&!isNaN(num))for(key=0;num>key;key++)arr[key+startIndex]=mixedVal;return arr}function objToArray(obj){if(!isObject(obj))return obj;if(!Object.keys(obj).every(function(key){return isInteger(key)}))return obj;var array=[];return each(obj,function(value,i){array[i]=value}),array}function simpleOp(op,data,path){var values=arguments.length<=3||void 0===arguments[3]?null:arguments[3],length=path.length,last=length-1,list=data;return each(path,function(key,i){switch((isNumeric(key)&&parseInt(key,10)>0||"0"===key)&&0!==key.indexOf("0")&&(key=parseInt(key,10)),op){case"insert":if(i===last)return list[key]=values,!1;null!=list[key]&&hasProp(list,key)||(list[key]={}),isCollection(list[key])||(list[key]={}),list=list[key];break;case"remove":if(i===last)return delete list[key],!1;if(null==list[key]||!hasProp(list,key))return!1;list=list[key]}}),data}function get(data,path){var defaultValue=arguments.length<=2||void 0===arguments[2]?null:arguments[2],parts=void 0,val=void 0;if(!isCollection(data))return defaultValue;if(empty(data)||null==path||""===path)return defaultValue;if(isString(path)||isNumeric(path))parts=(path+"").split(".");else{if(!isArray(path))return defaultValue;parts=path}return val=isCollection(data)?clone(data):data,each(parts,function(v){return isCollection(val)&&hasProp(val,v)?void(val=val[v]):(val=defaultValue,!1)}),val}function trim(input){return input.replace(/^\s+|\s+$/g,"")}function tokenize(str){var separator=arguments.length<=1||void 0===arguments[1]?",":arguments[1],left=arguments.length<=2||void 0===arguments[2]?"(":arguments[2],right=arguments.length<=3||void 0===arguments[3]?")":arguments[3];if(empty(str))return[];for(var depth=0,offset=0,buffer="",results=[],length=str.length,open=!1;length>=offset;){for(var tmpOffset=-1,offsets=[str.indexOf(separator,offset),str.indexOf(left,offset),str.indexOf(right,offset)],i=0;3>i;i++)-1!==offsets[i]&&(offsets[i]<tmpOffset||-1===tmpOffset)&&(tmpOffset=offsets[i]);if(-1!==tmpOffset){buffer+=str.substr(offset,tmpOffset-offset);var char=str.substr(tmpOffset,1);depth||char!==separator?buffer+=char:(results.push(buffer),buffer=""),left!==right?(char===left&&depth++,char===right&&depth--):char===left&&(open?depth--:(depth++,open=!0)),offset=++tmpOffset}else results.push(buffer+str.substr(offset)),offset=length+1}return empty(results)&&!empty(buffer)&&results.push(buffer),empty(results)?[]:results.map(function(val){return trim(val)})}function splitConditions(token){var conditions=!1,position=token.indexOf("[");return position>-1&&(conditions=token.substr(position),token=token.substr(0,position)),[token,conditions]}function matchToken(key,token){switch(token){case"{n}":return isNumeric(key);case"{s}":return isString(key);case"{*}":return!0;default:return isNumeric(token)?key==token:key===token}}function matches(data,selector){for(var identifier="(?:\\\\.|[\\w-_.]|[^\\x00-\\xa0])+",attributes=new RegExp("\\s*("+identifier+")(?:\\s*([><!]?[=]|[><])\\s*(\\/.*?\\/|"+identifier+")|)\\s*]","g"),cond=void 0;cond=attributes.exec(selector);){var attr=cond[1],op=cond[2]||null,val=cond[3]||null,hasProperty=hasProp(data,attr);if(empty(op)&&empty(val)&&!hasProperty)return!1;if(!hasProperty&&null==data[attr])return!1;var prop=hasProperty?prop=data[attr]:void 0,_isBoolean=isBoolean(prop)||"true"===prop||"false"===prop;if(_isBoolean&&isNumeric(val)?prop=prop?"1":"0":_isBoolean&&(prop=prop?"true":"false"),"="===op&&val&&"/"===val[0]&&"/"===val[val.length-1]){if(prop=isString(prop)||isNumeric(prop)?prop:"",!new RegExp(val.substr(1,val.length-2)).test(prop))return!1}else if("="===op&&prop!=val||"!="===op&&prop==val||">"===op&&val>=prop||"<"===op&&prop>=val||">="===op&&val>prop||"<="===op&&prop>val)return!1}return!0}function extract(data,path){if(!isCollection(data))return null;if(empty(path))return data;if(!/[{\[]/.test(path))return get(data,path,null);var key="__set_item__",tokens=void 0,context=babelHelpers.defineProperty({},key,[data]);return tokens=path.indexOf("[")<0?path.split("."):tokenize(path,".","[","]"),each(tokens,function(token){var next=[],_Text$splitConditions=splitConditions(token),_Text$splitConditions2=babelHelpers.slicedToArray(_Text$splitConditions,2),_token=_Text$splitConditions2[0],conditions=_Text$splitConditions2[1];each(context[key],function(item){each(item,function(v,k){matchToken(k,_token)&&next.push(v)})}),conditions&&!function(){var filter=[];each(next,function(item){isCollection(item)&&matches(item,conditions)&&filter.push(item)}),next=filter}(),context=babelHelpers.defineProperty({},key,next)}),context[key]}function insert(data,path){var value=arguments.length<=2||void 0===arguments[2]?null:arguments[2],noTokens=path.indexOf("[")<0;if(noTokens&&path.indexOf(".")<0)return data[path]=value,data;var tokens=void 0;if(tokens=noTokens?path.split("."):tokenize(path,".","[","]"),noTokens&&path.indexOf("{")<0)return simpleOp("insert",data,tokens,value);var token=tokens.shift(),nextPath=tokens.join("."),_Text$splitConditions=splitConditions(token),_Text$splitConditions2=babelHelpers.slicedToArray(_Text$splitConditions,2),_token=_Text$splitConditions2[0],conditions=_Text$splitConditions2[1];return each(data,function(v,k){matchToken(k,_token)&&(!conditions||matches(v,conditions))&&(data[k]=nextPath?insert(v,nextPath,value):merge(v,value))}),data}function remove(data,path){var noTokens=path.indexOf("[")<0,noExpansion=path.indexOf("{")<0;if(noExpansion&&noTokens&&path.indexOf(".")<0)return delete data[path],data;var tokens=noTokens?path.split("."):tokenize(path,".","[","]");if(noExpansion&&noTokens)return simpleOp("remove",data,tokens);var token=tokens.shift(),nextPath=tokens.join("."),_Text$splitConditions=splitConditions(token),_Text$splitConditions2=babelHelpers.slicedToArray(_Text$splitConditions,2),_token=_Text$splitConditions2[0],conditions=_Text$splitConditions2[1];return each(data,function(v,k){var match=matchToken(k,_token);match&&isCollection(v)?(conditions?matches(v,conditions)&&(nextPath?data[k]=remove(v,nextPath):delete data[k]):data[k]=remove(v,nextPath),empty(data[k])&&delete data[k]):match&&empty(nextPath)&&delete data[k]}),data}function combine(data,keyPath){var valuePath=arguments.length<=2||void 0===arguments[2]?null:arguments[2],groupPath=arguments.length<=3||void 0===arguments[3]?null:arguments[3];if(empty(data))return[];var keys=extract(data,keyPath),vals=void 0;if(empty(keys))return[];if(empty(valuePath)||(vals=extract(data,valuePath)),empty(vals)&&(vals=arrayFill(0,keys.length,null)),keys.length!==vals.length)return[];if(null!=groupPath){var group=extract(data,groupPath);if(!empty(group)){for(var c=keys.length,out={},i=0;c>i;i++)null!=group[i]&&hasProp(group,i)||(group[i]=0),null!=out[group[i]]&&hasProp(out,group[i])||(out[group[i]]={}),out[group[i]][keys[i]]=vals[i];return objToArray(out)}}return empty(vals)?[]:arrayCombine(keys,vals)}function check(data,path){var results=extract(data,path);return isCollection(results)?!empty(results):null!=results}function flatten(data){var separator=arguments.length<=1||void 0===arguments[1]?".":arguments[1];return _flatten(data,separator)}function _flatten(input,separator){var currentPath=arguments.length<=2||void 0===arguments[2]?null:arguments[2],results={},path=null;return isArray(input)&&0===input.length?(path=null==currentPath?0:currentPath,results[path]=input,results):(each(input,function(val,key){if(path=null==currentPath?key:""+currentPath+separator+key,isCollection(val)){var children=_flatten(val,separator,path);Object.keys(children).length>0&&(results=merge(results,children))}else void 0!==val&&(results[path]=val)}),objToArray(results))}function expand(data){var separator=arguments.length<=1||void 0===arguments[1]?".":arguments[1],results={};return each(data,function(value,flat){var keys=(flat+"").split(separator).reverse(),child={};child[keys.shift()]=value,each(keys,function(k){child=babelHelpers.defineProperty({},k,child)}),results=merge(results,child,!0)}),objToArray(results)}function map(data,path,callback){var values=objToArray(extract(data,path));return isArray(values)?values.map(callback):null}function reduce(data,path,callback){var values=objToArray(extract(data,path));return isArray(values)?values.reduce(callback):null}function CakeHash(){}var babelHelpers={};babelHelpers["typeof"]=function(obj){return obj&&"undefined"!=typeof Symbol&&obj.constructor===Symbol?"symbol":typeof obj},babelHelpers.defineProperty=function(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj},babelHelpers.slicedToArray=function(){function sliceIterator(arr,i){var _arr=[],_n=!0,_d=!1,_e=void 0;try{for(var _s,_i=arr[Symbol.iterator]();!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{!_n&&_i["return"]&&_i["return"]()}finally{if(_d)throw _e}}return _arr}return function(arr,i){if(Array.isArray(arr))return arr;if(Symbol.iterator in Object(arr))return sliceIterator(arr,i);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}();var classTypeList=["Boolean","Number","String","Function","Array","Date","RegExp","Object","Error","Symbol"],classTypes={};classTypeList.forEach(function(name){classTypes["[object "+name+"]"]=name.toLowerCase()});var VERSION="0.0.4";return CakeHash.VERSION=VERSION,CakeHash.get=get,CakeHash.extract=extract,CakeHash.insert=insert,CakeHash.remove=remove,CakeHash.combine=combine,CakeHash.check=check,CakeHash.flatten=flatten,CakeHash.expand=expand,CakeHash.map=map,CakeHash.reduce=reduce,CakeHash}); | ||
!function(global,factory){"object"==typeof exports&&"undefined"!=typeof module?module.exports=factory():"function"==typeof define&&define.amd?define(factory):global.CakeHash=factory()}(this,function(){"use strict";function getType(obj){return null==obj?obj+"":"object"===("undefined"==typeof obj?"undefined":babelHelpers["typeof"](obj))||"function"==typeof obj?classTypes[Object.prototype.toString.call(obj)]||"object":"undefined"==typeof obj?"undefined":babelHelpers["typeof"](obj)}function isArray(obj){return Array.isArray(obj)}function isObject(obj){return!isArray(obj)&&"object"===getType(obj)}function isNumber(obj){return"number"===getType(obj)}function isString(obj){return"string"===getType(obj)}function isBoolean(obj){return"boolean"===getType(obj)}function isCollection(obj){return isArray(obj)||isObject(obj)}function isNumeric(obj){var type=getType(obj);return("number"===type||"string"===type)&&obj-parseFloat(obj)+1>=0}function isInteger(obj){var type=getType(obj);return("number"===type||"string"===type)&&/^([1-9]\d*|0)$/.test(obj)}function empty(obj){return isArray(obj)?0===obj.length:isObject(obj)?0===Object.keys(obj).length:isNumeric(obj)?0===parseFloat(obj):!obj}function hasProp(obj,key){return obj&&obj.hasOwnProperty(key)}function clone(obj){var _isArray=isArray(obj),_isObject=isObject(obj);if(_isArray||_isObject){var result=_isArray?[]:{},key=void 0,val=void 0;for(key in obj)hasProp(obj,key)&&(val=obj[key],isCollection(val)&&(val=clone(val)),result[key]=val);return result}}function merge(obj,source){var deep=arguments.length<=2||void 0===arguments[2]?!1:arguments[2];return each(source,function(value,key){deep&&hasProp(obj,key)&&isCollection(value)?merge(obj[key],value,deep):obj[key]=value}),obj}function each(obj,iterate,context){if(null==obj)return obj;if(context=context||obj,isObject(obj)){for(var key in obj)if(hasProp(obj,key)&&iterate.call(context,obj[key],key)===!1)break}else if(isArray(obj)){var i=void 0,length=obj.length;for(i=0;length>i&&iterate.call(context,obj[i],i)!==!1;i++);}return obj}function arrayCombine(keys,values){var data={},keyCount=keys&&keys.length,i=0,key=void 0;if(!(isCollection(keys)&&isCollection(values)&&isNumber(keyCount)&&isNumber(values.length)&&keyCount))return null;if(keyCount!==values.length)return null;for(i=0;keyCount>i;i++)key=keys[i],isInteger(key)&&(key=parseInt(key,10)),data[key]=values[i];return objToArray(data)}function arrayFill(startIndex,num,mixedVal){var key=void 0,arr=[];if(!isNaN(startIndex)&&!isNaN(num))for(key=0;num>key;key++)arr[key+startIndex]=mixedVal;return arr}function objToArray(obj){if(!isObject(obj))return obj;if(!Object.keys(obj).every(function(key){return isInteger(key)}))return obj;var array=[];return each(obj,function(value,i){array[i]=value}),array}function simpleOp(op,data,path){var values=arguments.length<=3||void 0===arguments[3]?null:arguments[3],length=path.length,last=length-1,list=data;return each(path,function(key,i){switch((isNumeric(key)&&parseInt(key,10)>0||"0"===key)&&0!==key.indexOf("0")&&(key=parseInt(key,10)),op){case"insert":if(i===last)return list[key]=values,!1;null!=list[key]&&hasProp(list,key)||(list[key]={}),isCollection(list[key])||(list[key]={}),list=list[key];break;case"remove":if(i===last)return delete list[key],!1;if(null==list[key]||!hasProp(list,key))return!1;list=list[key]}}),data}function trim(input){return input.replace(/^\s+|\s+$/g,"")}function split(input,separator){var tokens=(input+"").split(separator),results=[],previousValue=null;return each(tokens,function(token){/^.*\\$/.test(token)?previousValue=token:(null!=previousValue&&(token=previousValue.slice(0,previousValue.length-1)+separator+token,previousValue=null),results.push(token))}),results}function tokenize(str){var separator=arguments.length<=1||void 0===arguments[1]?",":arguments[1],left=arguments.length<=2||void 0===arguments[2]?"(":arguments[2],right=arguments.length<=3||void 0===arguments[3]?")":arguments[3];if(empty(str))return[];for(var depth=0,offset=0,buffer="",results=[],length=str.length,open=!1;length>=offset;){for(var tmpOffset=-1,offsets=[str.indexOf(separator,offset),str.indexOf(left,offset),str.indexOf(right,offset)],i=0;3>i;i++)-1!==offsets[i]&&(offsets[i]<tmpOffset||-1===tmpOffset)&&(tmpOffset=offsets[i]);if(-1!==tmpOffset){buffer+=str.substr(offset,tmpOffset-offset);var char=str.substr(tmpOffset,1);depth||char!==separator||"\\"===str.substr(tmpOffset-1,1)?0===depth&&/^.*\\$/.test(buffer)?buffer=buffer.slice(0,buffer.length-1)+char:buffer+=char:(results.push(buffer),buffer=""),left!==right?(char===left&&depth++,char===right&&depth--):char===left&&(open?depth--:(depth++,open=!0)),offset=++tmpOffset}else results.push(buffer+str.substr(offset)),offset=length+1}return empty(results)&&!empty(buffer)&&results.push(buffer),empty(results)?[]:results.map(function(val){return trim(val)})}function splitConditions(token){var conditions=!1,position=token.indexOf("[");return position>-1&&(conditions=token.substr(position),token=token.substr(0,position)),[token,conditions]}function matchToken(key,token){switch(token){case"{n}":return isNumeric(key);case"{s}":return isString(key);case"{*}":return!0;default:return isNumeric(token)?key==token:key===token}}function matches(data,selector){for(var identifier="(?:\\\\.|[\\w-_.]|[^\\x00-\\xa0])+",attributes=new RegExp("\\s*("+identifier+")(?:\\s*([><!]?[=]|[><])\\s*(\\/.*?\\/|"+identifier+")|)\\s*]","g"),cond=void 0;cond=attributes.exec(selector);){var attr=cond[1],op=cond[2]||null,val=cond[3]||null,hasProperty=hasProp(data,attr);if(empty(op)&&empty(val)&&!hasProperty)return!1;if(!hasProperty&&null==data[attr])return!1;var prop=hasProperty?prop=data[attr]:void 0,_isBoolean=isBoolean(prop)||"true"===prop||"false"===prop;if(_isBoolean&&isNumeric(val)?prop=prop?"1":"0":_isBoolean&&(prop=prop?"true":"false"),"="===op&&val&&"/"===val[0]&&"/"===val[val.length-1]){if(prop=isString(prop)||isNumeric(prop)?prop:"",!new RegExp(val.substr(1,val.length-2)).test(prop))return!1}else if("="===op&&prop!=val||"!="===op&&prop==val||">"===op&&val>=prop||"<"===op&&prop>=val||">="===op&&val>prop||"<="===op&&prop>val)return!1}return!0}function get(data,path){var defaultValue=arguments.length<=2||void 0===arguments[2]?null:arguments[2],parts=void 0,val=void 0;if(!isCollection(data))return defaultValue;if(empty(data)||null==path||""===path)return defaultValue;if(isString(path)||isNumeric(path))parts=split(path,".");else{if(!isArray(path))return defaultValue;parts=path}return val=isCollection(data)?clone(data):data,each(parts,function(v){return isCollection(val)&&hasProp(val,v)?void(val=val[v]):(val=defaultValue,!1)}),val}function extract(data,path){if(!isCollection(data))return null;if(empty(path))return data;if(!/[{\[]/.test(path))return get(data,path,null);var key="__set_item__",tokens=void 0,context=babelHelpers.defineProperty({},key,[data]);return tokens=path.indexOf("[")<0?split(path,"."):tokenize(path,".","[","]"),each(tokens,function(token){var next=[],_Text$splitConditions=splitConditions(token),_Text$splitConditions2=babelHelpers.slicedToArray(_Text$splitConditions,2),_token=_Text$splitConditions2[0],conditions=_Text$splitConditions2[1];each(context[key],function(item){each(item,function(v,k){matchToken(k,_token)&&next.push(v)})}),conditions&&!function(){var filter=[];each(next,function(item){isCollection(item)&&matches(item,conditions)&&filter.push(item)}),next=filter}(),context=babelHelpers.defineProperty({},key,next)}),context[key]}function insert(data,path){var value=arguments.length<=2||void 0===arguments[2]?null:arguments[2],noTokens=path.indexOf("[")<0;if(noTokens&&path.indexOf(".")<0)return data[path]=value,data;var tokens=void 0;if(tokens=noTokens?path.split("."):tokenize(path,".","[","]"),noTokens&&path.indexOf("{")<0)return simpleOp("insert",data,tokens,value);var token=tokens.shift(),nextPath=tokens.join("."),_Text$splitConditions=splitConditions(token),_Text$splitConditions2=babelHelpers.slicedToArray(_Text$splitConditions,2),_token=_Text$splitConditions2[0],conditions=_Text$splitConditions2[1];return each(data,function(v,k){matchToken(k,_token)&&(!conditions||matches(v,conditions))&&(data[k]=nextPath?insert(v,nextPath,value):merge(v,value))}),data}function remove(data,path){var noTokens=path.indexOf("[")<0,noExpansion=path.indexOf("{")<0;if(noExpansion&&noTokens&&path.indexOf(".")<0)return delete data[path],data;var tokens=noTokens?path.split("."):tokenize(path,".","[","]");if(noExpansion&&noTokens)return simpleOp("remove",data,tokens);var token=tokens.shift(),nextPath=tokens.join("."),_Text$splitConditions=splitConditions(token),_Text$splitConditions2=babelHelpers.slicedToArray(_Text$splitConditions,2),_token=_Text$splitConditions2[0],conditions=_Text$splitConditions2[1];return each(data,function(v,k){var match=matchToken(k,_token);match&&isCollection(v)?(conditions?matches(v,conditions)&&(nextPath?data[k]=remove(v,nextPath):delete data[k]):data[k]=remove(v,nextPath),empty(data[k])&&delete data[k]):match&&empty(nextPath)&&delete data[k]}),data}function combine(data,keyPath){var valuePath=arguments.length<=2||void 0===arguments[2]?null:arguments[2],groupPath=arguments.length<=3||void 0===arguments[3]?null:arguments[3];if(empty(data))return[];var keys=extract(data,keyPath),vals=void 0;if(empty(keys))return[];if(empty(valuePath)||(vals=extract(data,valuePath)),empty(vals)&&(vals=arrayFill(0,keys.length,null)),keys.length!==vals.length)return[];if(null!=groupPath){var group=extract(data,groupPath);if(!empty(group)){for(var c=keys.length,out={},i=0;c>i;i++)null!=group[i]&&hasProp(group,i)||(group[i]=0),null!=out[group[i]]&&hasProp(out,group[i])||(out[group[i]]={}),out[group[i]][keys[i]]=vals[i];return objToArray(out)}}return empty(vals)?[]:arrayCombine(keys,vals)}function check(data,path){var results=extract(data,path);return isCollection(results)?!empty(results):null!=results}function flatten(data){var separator=arguments.length<=1||void 0===arguments[1]?".":arguments[1];return _flatten(data,separator)}function _flatten(input,separator){var currentPath=arguments.length<=2||void 0===arguments[2]?null:arguments[2],results={},path=null;return isArray(input)&&0===input.length?(path=null==currentPath?0:currentPath,results[path]=input,results):(each(input,function(val,key){if(key=(key+"").split(separator).join("\\"+separator),path=null==currentPath?key:""+currentPath+separator+key,isCollection(val)){var children=_flatten(val,separator,path);Object.keys(children).length>0&&(results=merge(results,children))}else void 0!==val&&(results[path]=val)}),objToArray(results))}function expand(data){var separator=arguments.length<=1||void 0===arguments[1]?".":arguments[1],results={};return each(data,function(value,flat){var keys=split(flat,separator).reverse(),child={};child[keys.shift()]=value,each(keys,function(k){child=babelHelpers.defineProperty({},k,child)}),results=merge(results,child,!0)}),objToArray(results)}function map(data,path,callback){var values=objToArray(extract(data,path));return isArray(values)?values.map(callback):null}function reduce(data,path,callback){var values=objToArray(extract(data,path));return isArray(values)?values.reduce(callback):null}function CakeHash(){}var babelHelpers={};babelHelpers["typeof"]=function(obj){return obj&&"undefined"!=typeof Symbol&&obj.constructor===Symbol?"symbol":typeof obj},babelHelpers.defineProperty=function(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj},babelHelpers.slicedToArray=function(){function sliceIterator(arr,i){var _arr=[],_n=!0,_d=!1,_e=void 0;try{for(var _s,_i=arr[Symbol.iterator]();!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{!_n&&_i["return"]&&_i["return"]()}finally{if(_d)throw _e}}return _arr}return function(arr,i){if(Array.isArray(arr))return arr;if(Symbol.iterator in Object(arr))return sliceIterator(arr,i);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}();var classTypeList=["Boolean","Number","String","Function","Array","Date","RegExp","Object","Error","Symbol"],classTypes={};classTypeList.forEach(function(name){classTypes["[object "+name+"]"]=name.toLowerCase()});var VERSION="0.0.5";return CakeHash.VERSION=VERSION,CakeHash.get=get,CakeHash.extract=extract,CakeHash.insert=insert,CakeHash.remove=remove,CakeHash.combine=combine,CakeHash.check=check,CakeHash.flatten=flatten,CakeHash.expand=expand,CakeHash.map=map,CakeHash.reduce=reduce,CakeHash}); |
{ | ||
"name": "cake-hash", | ||
"version": "0.0.4", | ||
"version": "0.0.5", | ||
"description": "CakePHP in Utility.Hash class like a collection manipulation. In JavaScript.", | ||
@@ -5,0 +5,0 @@ "main": "cake-hash.js", |
@@ -99,3 +99,3 @@ cake-hash | ||
| Matcher | Definition | | ||
| :--------------| :-----------------------------------------------------------------------------| | ||
| :------------- | :---------------------------------------------------------------------------- | | ||
| `[id]` | Match elements with a given array key. | | ||
@@ -110,2 +110,22 @@ | `[id=2]` | Match elements with id equal to 2. | | ||
### Escape the separator | ||
The separator in path syntax can be escaped by using the `\`. | ||
**Example :** | ||
```javascript | ||
const data = { | ||
"index.html": { | ||
css: { | ||
"style.css": "* {box-sizing: border-box}" | ||
} | ||
} | ||
}; | ||
let result = CakeHash.get(data, "index\\.html.css.style\\.css"); | ||
console.log(result); // * {box-sizing: border-box} | ||
``` | ||
## API | ||
@@ -112,0 +132,0 @@ |
@@ -12,3 +12,3 @@ import get from "./get" | ||
const VERSION = "0.0.4"; | ||
const VERSION = "0.0.5"; | ||
@@ -15,0 +15,0 @@ |
import * as Collection from "./utils/collection" | ||
import * as Text from "./utils/text" | ||
@@ -7,3 +8,3 @@ export default function expand(data, separator = ".") { | ||
Collection.each(data, (value, flat) => { | ||
let keys = (flat + "").split(separator).reverse(); | ||
let keys = Text.split(flat, separator).reverse(); | ||
let child = {}; | ||
@@ -10,0 +11,0 @@ child[keys.shift()] = value; |
@@ -24,3 +24,3 @@ import * as Core from "./utils/core" | ||
if (path.indexOf("[") < 0) { | ||
tokens = path.split("."); | ||
tokens = Text.split(path, "."); | ||
} else { | ||
@@ -27,0 +27,0 @@ tokens = Text.tokenize(path, ".", "[", "]"); |
@@ -20,2 +20,3 @@ import * as Core from "./utils/core" | ||
Collection.each(input, function(val, key) { | ||
key = (key + "").split(separator).join(`\\${separator}`); | ||
path = currentPath == null ? key : `${currentPath}${separator}${key}`; | ||
@@ -22,0 +23,0 @@ if (Core.isCollection(val)) { |
import * as Core from "./utils/core" | ||
import * as Collection from "./utils/collection" | ||
import * as Text from "./utils/text" | ||
@@ -16,3 +17,3 @@ export default function get(data, path, defaultValue = null) { | ||
if (Core.isString(path) || Core.isNumeric(path)) { | ||
parts = (path + "").split("."); | ||
parts = Text.split(path, "."); | ||
} else { | ||
@@ -19,0 +20,0 @@ if (!Core.isArray(path)) { |
@@ -13,3 +13,3 @@ const classTypeList = ["Boolean", "Number", "String", "Function", "Array", "Date", "RegExp", "Object", "Error", "Symbol"]; | ||
} | ||
return typeof obj === "object" || typeof obj === "function" ? | ||
return typeof obj === "object" || typeof obj === "function" ? | ||
classTypes[Object.prototype.toString.call(obj)] || "object" : | ||
@@ -16,0 +16,0 @@ typeof obj; |
@@ -10,2 +10,23 @@ import * as Core from "./core" | ||
export function split(input, separator){ | ||
const tokens = (input + "").split(separator); | ||
const results = []; | ||
let previousValue = null; | ||
Collection.each(tokens, (token) => { | ||
if (/^.*\\$/.test(token)) { | ||
previousValue = token; | ||
} else { | ||
if (previousValue != null) { | ||
token = previousValue.slice(0, previousValue.length - 1) + separator + token; | ||
previousValue = null; | ||
} | ||
results.push(token); | ||
} | ||
}); | ||
return results; | ||
} | ||
export function tokenize(str, separator = ",", left = "(", right = ")") { | ||
@@ -35,10 +56,15 @@ if( Core.empty(str) ){ | ||
} | ||
// console.log(depth, buffer); | ||
if (tmpOffset !== -1) { | ||
buffer += str.substr(offset, (tmpOffset - offset)); | ||
let char = str.substr(tmpOffset, 1); | ||
if (!depth && char === separator) { | ||
if (!depth && char === separator && str.substr(tmpOffset - 1, 1) !== "\\") { | ||
results.push(buffer); | ||
buffer = ""; | ||
} else { | ||
buffer += char; | ||
if (depth === 0 && /^.*\\$/.test(buffer)) { | ||
buffer = buffer.slice(0, buffer.length - 1) + char; | ||
} else { | ||
buffer += char; | ||
} | ||
} | ||
@@ -45,0 +71,0 @@ if (left !== right) { |
@@ -182,2 +182,13 @@ import assert from "power-assert" | ||
assert(Hash.get(data, "a.b.c.d") === 1); | ||
data = { | ||
"example.com": { | ||
"path": { | ||
"to": { | ||
"index.html": "Hello World" | ||
} | ||
} | ||
} | ||
}; | ||
assert(Hash.get(data, "example\\.com.path.to.index\\.html") === "Hello World"); | ||
}); | ||
@@ -419,2 +430,22 @@ | ||
}); | ||
it("FilenameKey", () => { | ||
let data = { | ||
"cake-hash.min.js": [ | ||
{keyword: "array"}, | ||
{keyword: "object"}, | ||
{keyword: "utility"}, | ||
{keyword: "browser"}, | ||
{keyword: "client"}, | ||
{keyword: "server"}, | ||
{keyword: "cakephp"} | ||
] | ||
}; | ||
assert.deepEqual(Hash.extract(data, "cake-hash\\.min\\.js.{n}[keyword=/^(a|c)/]"), [ | ||
{keyword: "array"}, | ||
{keyword: "client"}, | ||
{keyword: "cakephp"} | ||
]); | ||
}); | ||
}); | ||
@@ -725,2 +756,16 @@ | ||
}); | ||
data = [ | ||
{"index.html": {title: "Dashboard", body: "Dashboard Page"}}, | ||
{"about.html": {title: "About", body: "About Page"}}, | ||
{"./path/to/file.bundle.js": {title: "Bundle File", body: "Hello"}} | ||
]; | ||
assert.deepEqual(Hash.flatten(data, "."), { | ||
"0.index\\.html.title": "Dashboard", | ||
"0.index\\.html.body": "Dashboard Page", | ||
"1.about\\.html.title": "About", | ||
"1.about\\.html.body": "About Page", | ||
"2.\\./path/to/file\\.bundle\\.js.title": "Bundle File", | ||
"2.\\./path/to/file\\.bundle\\.js.body": "Hello" | ||
}); | ||
}); | ||
@@ -781,2 +826,17 @@ | ||
}); | ||
data = { | ||
"https://github\\.com/user/.repo.123.body": "CakePHP", | ||
"https://github\\.com/user/.repo.124.body": "CakeHash", | ||
"https://github\\.com/user/.repo.125.body": "npm" | ||
}; | ||
assert.deepEqual(Hash.expand(data), { | ||
"https://github.com/user/": { | ||
repo: { | ||
123: {body: "CakePHP"}, | ||
124: {body: "CakeHash"}, | ||
125: {body: "npm"} | ||
} | ||
} | ||
}); | ||
}); | ||
@@ -783,0 +843,0 @@ |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
90260
2025
580