javascript: How to make a directory in filetree-like structure? - javascript

I have code listed below. All "Tree" class works fine. I need help with "makekDir" function (in Node class), it should create new children tree (directory). This code in "makekDir" function this.findNode(filepath) always return null. I can't find how to fix it. Can any one help, or give advice how to fix it p.s. sorry for the big chunk of code, don't know would it be understandable if I post only Node class
import path from 'path';
//this class works fine
class Tree {
constructor(key, meta, parent) {
this.parent = parent;
this.key = key;
this.meta = meta;
this.children = new Map();
}
getKey() {
return this.key;
}
getMeta() {
return this.meta;
}
addChild(key, meta) {
const child = new Tree(key, meta, this);
this.children.set(key, child);
return child;
}
getChild(key) {
return this.children.get(key);
}
hasChild(key) {
return this.children.has(key);
}
getDeepChild(dirs = []) {
if (dirs.length === 0 || !Array.isArray(dirs)) {
console.log('not array');
return null;
}
const [first, ...rest] = dirs;
console.log(first, ...rest);
console.log (this);
if (this.hasChild(first)) {
return rest.length === 0
? this.getChild(first)
: this.getChild(first).getDeepChild(rest);
}
return null;
}
}
class Node {
constructor() {
this.tree = new Tree('/', { type: 'dir' });
}
///// I need help with this function
makekDir(filepath) {
const { dir } = path.parse(filepath);
const subtree = this.findNode(filepath);
return subtree.addChild(dir, { type: 'dir' });
}
/////
findNode(filepath) {
const parts = filepath.split(path.sep).filter((item) => item !== '');
return parts.length === 0 ? this.tree : this.tree.getDeepChild(parts);
}
}
console.log(new Node().makekDir('/etc'));

Related

LIVR Validate if element in object is empty array

I have LIVR in a project i'm working now and is quite unclear to me how this work. I can't understand how to create new rules for custom validation.
Here's the code:
LIVR.Validator.defaultAutoTrim(true);
let validator = new LIVR.Validator({});
LIVR.Validator.registerDefaultRules({
nested_object_value() {
return function (value) {
if (!value || (value && !value.value || value === [])) {
return 'REQUIRED';
}
return '';
};
},
max_number_advancement() {
return function (value) {
if (value > 100) {
return 'MAX_NUMBER';
}
return '';
};
},
required_if_activity_present() {
return function (value, allValue) {
if (allValue.activitycycletype && !value || allValue.requestpeople === []) {
console.log(first)
return 'REQUIRED_IF_CYCLETYPE';
}
return '';
};
},
});
And this is how its used:
validationForm = () => {
const { formValue, updateErrors } = this.props;
const validData = validator.validate(formValue);
console.log(formValue)
if (!validData) {
const errorsValidator = validator.getErrors();
if (errorsValidator && Object.keys(errorsValidator).length > 0) {
const newErrors = {};
Object.keys(errorsValidator).forEach((error) => {
newErrors[error] = errorsValidator[error];
});
updateErrors(newErrors);
}
blame(t('validation-error'));
return false;
}
updateErrors({});
return true;
}
Opening the form with this validation in the app, seems to call only the last method required_if_activity_present().
What i expect here is that i can create a new method inside registerDefaultRules(), that is a LIVR method, like this:
LIVR.Validator.registerDefaultRules({
re quired_not_empty() {
return function (value) {
if (!value) {
return 'REQUIRED';
}
return '';
};
},
... //other methods
}
but seems not working, the newer method is not being called at all by validator.validate()
Anyone know how to create a new rules where i can check if an element inside the object that has to be validate is an empty array?
Because seems that LIVR doesn't return a validation error in this case, but only on empty string and null values.
Thanks in advance

Vue 3 changing the length of both arrays have same values intially

I am using vue 3 where is i am receiving an array of associate schedule from server. Now i am saving this schedule to 2 arrays. I am doing this because i need the original fetched data later after doings changes in associate list array which is my first array.
associateList
orignalList
The problem is when I am replacing the associate array after doing changes with original array .No nothing works infact original list contains same changes which i did on associate list array even i have not touched the original list anywhere in my code just saving the data from response on it. I just want the original res on original list array so i can replace associate list with original array when watch function detect changes in attendance list array.
<script lang="ts">
import { Options, Vue } from "vue-class-component";
import ApprovalService from "../../service/ApprovalService";
import Toaster from "../../helpers/Toaster";
import moment from "moment";
import { camelCase } from "lodash";
import {
ScheduleList,
AttendanceList,
ApprovedList,
} from "../hoursApproval/IHoursAppoval";
import VueCal from "vue-cal";
import "vue-cal/dist/vuecal.css";
import AssociatePinVerification from "../../components/AssociatePinVerification.vue";
#Options({
components: { VueCal, AssociatePinVerification },
watch: {
attendanceList() {
const oL = this.orignalList;
alert('orgi'+oL.length);
this.associateList = this.orignalList;
this.checkScheduleContainsLogedHrs();
},
},
})
export default class HoursApproval extends Vue {
private ApprovalTxn;
private scheduleID = "";
private toast;
private orignalList: ScheduleList[] = [];
private associateList: ScheduleList[] = [];
private approvedList: ScheduleList[] = [];
private attendanceList: AttendanceList[] = [];
private approveManually = {
hours: 0,
freezed: false,
shiftDate: "",
counterId: 0,
};
//DEFAULT METHOD OF TYPE SCRIPT
//CALLING WHENEVER COMPONENT LOADS
created() {
this.ApprovalTxn = new ApprovalService();
this.toast = new Toaster();
}
mounted() {
this.getSchedule();
}
getSchedule() {
this.ApprovalTxn.getAssociateShifts(this.searchDate).then((res) => {
const d = this.camelizeKeys(res);
const s = d.employeeList.scheduleList;
if (s != null)
{
this.orignalList = this.camelizeKeys(d.employeeList.scheduleList);
this.associateList = this.camelizeKeys(d.employeeList.scheduleList);
}
else
{
this.associateList = [];
this.orignalList = [];
}
this.scheduleID = d.employeeList.id;
this.weekStartingDate = d.postStartingDate;
this.weekEndingDate = d.postEndingDate;
this.weekNo = d.weekNo;
});
}
camelizeKeys = (obj) => {
if (Array.isArray(obj)) {
return obj.map((v) => this.camelizeKeys(v));
} else if (obj !== null && obj.constructor === Object) {
return Object.keys(obj).reduce(
(result, key) => ({
...result,
[camelCase(key)]: this.camelizeKeys(obj[key]),
}),
{}
);
}
return obj;
};
formatDate(value) {
if (value) {
return moment(String(value)).format("DD-MM-YYYY");
}
}
updateAssociateLogin() {
if (
this.loginDetails.loginTime == "" ||
this.loginDetails.logoutTime == "" ||
this.loginDetails.loginDate == ""
) {
this.toast.showWarning(
"Please set date login and logout timings for associate to proceed"
);
} else {
this.associateList = [];
this.ApprovalTxn.updateAssociateLogin(
this.loginDetails.loginTime,
this.loginDetails.attendenceID,
this.managerApproved,
this.loginDetails.logoutTime,
this.loginDetails.loginDate,
this.weekStartingDate,
this.weekEndingDate
).then((res) => {
this.toast.handleResponse(res);
alert(this.orignalList.length);
// this.associateList = this.orignalList;
const d = this.camelizeKeys(res);
//DOING THIS TO CHNAGE THE RE ACTIVITY OF VUE
//this.modifyTimings();
this.attendanceList = d.data;
//alert(this.orignalList.length);
//console.log(this.associateList);
});
this.loginHoursDialog = false;
}
}
}
</script>

PrimeNG p-table header select all persistence with lazy loading and pagination

Current config (cannot update it to latest):
"#angular/cli": "^7.3.9",
"primeng": "7.0.5",
I have a PrimeNG p-table that has lazy loaded data with pagination.
There is an issue open for it on PrimeNG GitHub too - https://github.com/primefaces/primeng/issues/8139
Stackblitz link is already attached in that issue so didn't create a new one.
Scenario:
One 1st page, some rows are selected via checkbox selection.
On 2nd page, Select All checkbox from the header is selected and all rows on 2nd page is auto-selected.
Now when navigated to the first page, the selections from here are reset. But the Select All checkbox in the header is still checked.
Would like to know if anyone has a workaround for this issue?
Any help is appreciated.
Edit:
Solution found in another similar GitHub issue: https://github.com/primefaces/primeng/issues/6482
Solution:
https://github.com/primefaces/primeng/issues/6482#issuecomment-456644912
Can someone help with the implementation of the override in an Angular 7/8 application. Not able to understand as how to get the TableHeaderCheckbox reference and override the prototype.
Well, the solution to the problem is still not added to the PrimeNG repo and so even the latest package does not have it solved.
For time being, use the solution mentioned in the question under Edit
To answer the question that I have asked under the Edit, check below:
// In some service file:
import { Table, TableHeaderCheckbox } from 'primeng/table';
import { ObjectUtils } from 'primeng/components/utils/objectutils';
import { uniq, each, intersection, map, remove } from 'lodash';
#Injectable()
export class BulkSelectAllPagesService {
overridePrimeNGTableMethods() {
TableHeaderCheckbox.prototype.updateCheckedState = function () {
const currentRows = map(this.dt.value, this.dt.dataKey);
const selectedRows = map(this.dt.selection, this.dt.dataKey);
this.rowsPerPageValue = this.dt.rows;
const commonRows = intersection(currentRows, selectedRows);
return commonRows.length === currentRows.length;
};
Table.prototype.toggleRowsWithCheckbox = function (event, check) {
let _selection;
if (!check) {
_selection = this.value.slice();
each(_selection, (row) => {
const match = {}; match[this.dataKey] = row[this.dataKey];
remove(this._selection, match);
});
} else {
_selection = check ? this.filteredValue ? this.filteredValue.slice() : this.value.slice() : [];
each(this._selection, (row) => {
const match = {}; match[this.dataKey] = row[this.dataKey];
remove(_selection, match);
});
this._selection = this._selection.concat(_selection);
}
this.preventSelectionSetterPropagation = true;
this.updateSelectionKeys();
this.selectionChange.emit(this._selection);
this.tableService.onSelectionChange();
this.onHeaderCheckboxToggle.emit({
originalEvent: event,
affectedRows: _selection,
checked: check
});
};
}
// In app.component.ts
import { Component, OnInit } from '#angular/core';
import { BulkSelectAllPagesService } from 'PATH_TO_THE_FILE/bulk-select-all-pages.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
constructor(
private bulkSelectAllPagesService: BulkSelectAllPagesService) {
}
ngOnInit() {
this.bulkSelectAllPagesService.overridePrimeNGTableMethods();
}
}
Ofcourse need to include the service file in the providers[] in the app.module.ts
Will create a stackblitz and add later.
Improved version to handle rowspan grouped data:
overridePrimeNGTableMethods() {
TableHeaderCheckbox.prototype.updateCheckedState = function () {
const currentRows = map(this.dt.value, this.dt.dataKey);
const uniqueCurrentRows = uniq(currentRows);
const selectedRows = map(this.dt.selection, this.dt.dataKey);
this.rowsPerPageValue = this.dt.rows;
const commonRows = intersection(currentRows, selectedRows);
if (currentRows.length) {
return commonRows.length === uniqueCurrentRows.length;
} else {
return false;
}
};
Table.prototype.toggleRowWithCheckbox = function (event, rowData) {
const findIndexesInSelection = (selection: any = [], data: any = {}, dataKey: any) => {
const indexes = [];
if (selection && selection.length) {
selection.forEach((sel: any, i: number) => {
if (data[dataKey] === sel[dataKey]) {
indexes.push(i);
}
});
}
return indexes;
};
this.selection = this.selection || [];
const selected = this.isSelected(rowData);
const dataKeyValue = this.dataKey ? String(ObjectUtils.resolveFieldData(rowData, this.dataKey)) : null;
this.preventSelectionSetterPropagation = true;
if (selected) {
const selectionIndexes = findIndexesInSelection(this.selection, rowData, this.dataKey);
const selectedItems = this.selection.filter((val: any) => {
return val[this.dataKey] === rowData[this.dataKey];
});
this._selection = this.selection.filter((val: any, i: number) => {
return selectionIndexes.indexOf(i) === -1;
});
this.selectionChange.emit(this.selection);
selectedItems.forEach((selectedItem: any, index: number) => {
this.onRowUnselect.emit({ originalEvent: event.originalEvent, index: event.rowIndex + index, data: selectedItem, type: 'checkbox' });
});
delete this.selectionKeys[rowData[this.dataKey]];
} else {
let rows = [rowData];
if (dataKeyValue) {
rows = this.value.filter(val => {
return (val[this.dataKey]).toString() === dataKeyValue;
});
}
this._selection = this.selection ? this.selection.concat(rows) : rows;
this.selectionChange.emit(this.selection);
this.onRowSelect.emit({ originalEvent: event.originalEvent, index: event.rowIndex, data: rowData, type: 'checkbox' });
if (dataKeyValue) {
this.selectionKeys[dataKeyValue] = 1;
}
}
this.tableService.onSelectionChange();
if (this.isStateful()) {
this.saveState();
}
};
Table.prototype.toggleRowsWithCheckbox = function (event, check) {
let _selection;
if (!check) {
_selection = this.value.slice();
each(_selection, (row) => {
const match = {}; match[this.dataKey] = row[this.dataKey];
remove(this._selection, match);
});
} else {
_selection = check ? this.filteredValue ? this.filteredValue.slice() : this.value.slice() : [];
each(this._selection, (row) => {
const match = {}; match[this.dataKey] = row[this.dataKey];
remove(_selection, match);
});
this._selection = this._selection.concat(_selection);
}
this.preventSelectionSetterPropagation = true;
this.updateSelectionKeys();
this.selectionChange.emit(this._selection);
this.tableService.onSelectionChange();
this.onHeaderCheckboxToggle.emit({
originalEvent: event,
affectedRows: _selection,
checked: check
});
};
}

Issues printing my groups tree in nodeJS app

I'm trying to print all created groups and they're children so it'll look like that:
[ [ 'Father1', 'Child1', 'Child2', 'Child3' ],
[ 'Father1', 'Child1', 'Child4' ],
[ 'Father1', 'Child1', 'Child5' ] ]
The problems I encountered are varied. from:
var keys = name.keys(o); ^ TypeError: name.keys is not a function to total stack overflow, iv'e debugged the printPath function and it's doing it's job separately but not with my final tree structure.
My tree and print function looks like that:
groups.js:
class groups {
constructor() {
this.root = new Group('root');
}
printPath(name){
this.root.getPath(name)
}
group.js:
class Group {
constructor(name, parent) {
this.name = name;
this.parent = parent || null;
this.children = [];
this.users = new users || null;
}
getPath(name) {
function iter(o, p) {
var keys = name.keys(o);
if (keys.length) {
return keys.forEach(function (k) {
iter(o[k], p.concat(k));
});
}
result.push(p);
}
var result = [];
iter(name, []);
return result;
}
Edit:
For creating a group i'm using a menu handler function:
function createGroup(callback) {
rl.question('Add name for father group: \n', (parent) => {
let parentGroup = programdata.groups.findGroupByName(parent);
if (!parentGroup) {
parentGroup = programdata.groups.root;
}
rl.question('name of new group\n', (groupName) => {
parentGroup.setChildren(new Group(groupName, parentGroup));
console.log(parentGroup);
callback();
});
})
}
findGroupByNameis a nice recursion i made that finds nested groups (feel free to use!) sitting in class groups.
findGroupByName(name) {
if (!name) return null;
return this._findGroupByNameInternal(this.root, name);
}
_findGroupByNameInternal(group, name) {
if (!group) return null;
if (group.name === name) return group;
for (const g of group.children) {
const result = this._findGroupByNameInternal(g, name);
if (!result) continue;
return result;
}
}
And setChildren function placed in class Group:
setChildren(child) {
this.children.push(child);
}
EDIT:
Thank you for the answer, could you please help me realize your method in my menu handler? iv'e tried this: and it giving me nothing.
function createGroup(callback) {
rl.question('Add name for father group: \n', (parent) => {
let parentGroup = programdata.groups.findGroupByName(parent);
let treePath = Group.root.printPath();
if (!parentGroup) {
parentGroup = programdata.groups.root;
}
rl.question('name of new group\n', (groupName) => {
parentGroup.addChild(new Group(groupName, parentGroup));
console.log(treePath);
callback();
});
})
}
The root cause you got the error TypeError: name.keys is not a function is that a string is passed into getPath(name) as argument name, you know the JS string object doesn't have a function property keys.
I refactor your code and fix some error, here is the testable version. Pls put them into the same folder and run test.js.
group.js
class Group {
constructor(name, parent) {
this.name = name;
this.parent = parent || null; // Point to this group's father
this.children = []; // Children of this group, can be sub-group or string
if (!!parent) { // Link to the father
parent.addChild(this);
}
// this.users = new users || null; // Useless, remove it.
}
addChild(...args) {
for(let o in args) {
this.children.push(args[o]);
}
}
/**
* Recursion to build the tree
* #param group
* #returns {*}
*/
iter(group) {
let children = group.children;
if (Array.isArray(children)) { // If the child is a group
if (children.length > 0) {
let result = [];
result.push(group.name);
for (let child of children) {
result.push(group.iter(child));
}
return result;
}
else {
return [];
}
}
else { // If the group is a string
return group;
}
}
getPath() {
return this.iter(this);
}
}
module.exports = Group;
groups.js
let Group = require('./group');
class Groups {
constructor() {
this.root = new Group('root');
}
printPath() {
return this.root.getPath();
}
}
module.exports = Groups;
test.js
let Group = require('./group');
let Groups = require('./groups');
// Root
let rootGroups = new Groups();
// Group 1
let group1 = new Group('Father1', rootGroups.root);
group1.addChild('Child1', 'Child2', 'Child3');
// Group 2
let group2 = new Group('Father1', rootGroups.root);
group2.addChild('Child1', 'Child4');
// Group 3
let group3 = new Group('Father1', rootGroups.root);
group3.addChild('Child1', 'Child5');
let treePath = rootGroups.printPath();
console.log(treePath);
The output is:
[ 'root',
[ 'Father1', 'Child1', 'Child2', 'Child3' ],
[ 'Father1', 'Child1', 'Child4' ],
[ 'Father1', 'Child1', 'Child5' ] ]
Process finished with exit code 0
Enjoy it :)
Ok, found a solution.
Treeshow(){
var node = this.root;
var depth = '-'
recurse( node );
function recurse( node) {
depth +='-'
console.log(depth+node.name);
for (var child in node.children ) {
recurse(node.children[child]);
}
depth = depth.slice(0, -1);
}
}
that will show my tree just like that:
--root
---FooFather
----BarSemiFather
-----FooChild
------BarBaby

Is it possible to Proxy an extended class in javascript

I'm trying to Proxy an inheritance structure from within a node module and allow the client to instantiate a new Class A. Currently when trying to access class B's parent methods I get a.parentMethod is not a function
handler.js ->
module.exports = {
get(target, key, receiver) {
return target.getAttribute(key)
},
set(target, key, value, receiver) {
return target.setAttribute(key, value)
}
}
A.js ->
const handler = require('handler')
class B {
constructor(data) {
this.data = data
}
parentMethod() {
... do stuff
}
}
class A extends B {
constructor(data){
super(data)
}
}
module.exports = function(data) {
return new Proxy(new A(data), handler)
}
////
const A = require('A')
var a = new A
a.parentMethod()
Where am I going wrong with this structure? I'm new to Proxy!
Thanks
EDIT -
Further context:
I'm trying to keep sets of properties in sync based on a valueSchema I have defined. When I set Artwork.title I need Artwork['Artwork Title'] to be updated with the same value. Likewise when I retrieve Artwork.title I get the value of Artwork['Artwork Title']. Hopefully this helps a bit. I'm stuck at the above error so I can't be sure what I've written actually works yet! I'm trying to debug why the function can't be found first...
class Instance {
constructor(data) {
this._valueAttributes = {}
}
setAttribute(key, value) {
if (this._isValueAttribute(key)) {
return this._getSetValueAttribute(key, value)
}
throw Error('Cannot set invalid property '+key+' on instance.')
}
getAttribute(key) {
if (this._isValueAttribute(key)) {
return this._getSetValueAttribute(key)
}
}
_getSetValueAttribute(key, value) {
let schemaKey = this._getSchemaKey(key)
if (_.isFunction(schemaKey)) {
return alias(data)
}
if (value === undefined) {
return this._valueAttributes[schemaKey]
}
return this._valueAttributes[schemaKey] = value
}
_isValueAttribute(key) {
return _.keys(this._valueSchema).indexOf(key) === -1
}
}
class Artwork extends Instance {
constructor() {
this._valueSchema = {
medium: 'Artwork Medium',
title: 'Artwork Title'
}
}
}
///
a = new Artwork
a.title = 'thing'
a['Artwork Medium'] = 'medium';
I need
a.title == a['Artwork Title']
a['Artwork Medium'] == a.medium
It's very likely I've royally screwed it all up. I've assumed that I can access __valueSchema on the child from the parent. Is this not possible?

Categories