UNPKG

1.59 kBJavaScriptView Raw
1// Copyright 2019 Zaiste & contributors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14function pick(obj, keys) {
15 return keys.reduce((acc, k) => {
16 acc[k] = obj[k];
17 return acc;
18 }, {});
19}
20
21function isObject(_) {
22 return !!_ && typeof _ === 'object';
23 //return !!_ && _.constructor === Object;
24}
25
26const substitute = (template, data) => {
27 const start = '{{';
28 const end = '}}';
29 const path = '[a-z0-9_$][\\.a-z0-9_]*';
30 const pattern = new RegExp(start + '\\s*(' + path + ')\\s*' + end, 'gi');
31
32 return template.replace(pattern, (tag, token) => {
33 let path = token.split('.');
34 let len = path.length;
35 let lookup = data;
36 let i = 0;
37
38 for (; i < len; i++) {
39 lookup = lookup[path[i]];
40
41 if (lookup === undefined) {
42 throw new Error(`substitue: '${path[i]}' not found in '${tag}'`);
43 }
44
45 if (i === len - 1) {
46 return lookup;
47 }
48 }
49 });
50};
51
52const compose = (...functions) => args => functions.reduceRight((arg, fn) => fn(arg), args);
53
54module.exports = { pick, isObject, substitute, compose };